Why y---3
statement behave like y = 3
? Can someone explain?
#include <stdio.h>
main(){
int x=-2, y=4, z;
y---3;
printf("%d",y);
}
Why y---3
statement behave like y = 3
? Can someone explain?
#include <stdio.h>
main(){
int x=-2, y=4, z;
y---3;
printf("%d",y);
}
C tries to read its tokens greedily, i.e. it tries to read and match as long sequences as it can. Therefore the ---
will be parsed as -- -
, which means you have y-- - 3
.
Since you don't store the result anywhere, the only relevant bit is y--
, which decreases y
from 4
to 3
.
This:
y---3;
Parses as:
y-- - 3;
So this expression decrements y
, takes the prior value of y
and subtracts 3 from it. The result of the expression (i.e. 1) is discarded because it is used as a statement by itself.
y---3;
is not the same as y = 3
.
y--3
is parsed as (y--) - 3
, and the final result of the subtraction is discarded. So the only side effect of y--
is retained, decrementing 1
from the earlier value of y
, which was 4
.
For that matter, y---n
, where n
is any integer will produce the same result for the next print statement.
If you compile this with warnings enabled, your compiler will tell you (amongst other warnings) something like:
test.c:6:7: warning: value computed is not used [-Wunused-value]
y---3;
~~~^~
In this case, the code, written more readably, is:
y-- - 3;
which is equivalent to:
y - 3;
y -= 1;
The first of these statements is redundant, because you are computing a value and then discarding it.