This particular code
if (!x--)
where x
is an int
and !
is the NOT operator.
What does this code do and why?
There are two operators here, the first is the post-decrement operator --
which means reduce x
by 1 and return the original value.
The second is the !
operator which is the logical NOT operator, which returns true
if its operand is zero, and false
if it is not zero.
--
has higher precedence so it will be evaluated first.
Thus the code reduces x
by 1, and then executes the body of the conditional if x
was 0 before the line was reached.
--
has higher precedence doesn't mean it will be done first. With post-increment and post-decrement, the current value is returned and then the increment or decrement happens later. The higher precedence just means the decrement won't be applied to the result of !si
, which wouldn't make any sense anyway, that result not being an lvalue.
!(x--)
rather than (!x)--
.
Jul 17, 2014 at 8:47
x--
returns the actual value of x
, not x-1
, which is then evaluated by the !
operator. Or am I wrong? EDIT: (!x)--
would of course be wrong because decrementing a boolean... my bad. But I feel like your answer is unclear about the value that gets evaluated by the !
...
Jul 17, 2014 at 9:45
Since the "--" is used as a postfix operator, it decrements the variable 'x' only after 'x'' is evaluated.
If x
was zero before, then the true part of the if statement will be executed.
x
will be decremented regardless of whether it was zero or not.
si
, and if it was 0 before the statement, the body will be executed.
Jul 17, 2014 at 4:54
true
, and zero is the onlyint
that isfalse
. The expression you mentioned, decrementssi
by one, and if it was zero before decrement returnstrue
, otherwise returnsfalse
.