2

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);
}
alinsoar
  • 15,386
  • 4
  • 57
  • 74

4 Answers4

8

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
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.

dbush
  • 205,898
  • 23
  • 218
  • 273
2

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

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.

alani
  • 12,573
  • 2
  • 13
  • 23