-1

I came across this question and expected it to show up as a compile time error but to my surprise each statement separated by comma is executed and the final value is assigned to the variable.

int a,b=5;
a=(b++,++b,b*4,b-3);
printf("%d",a);

Output is 4

This output is exactly what should be the printed when each of those comma separated statements are executed separately. What I am not understanding is how and why does C allow this and how does compiler process this.

crappyprog
  • 56
  • 1
  • 6

2 Answers2

4

See What does the comma operator , do?

After understanding how the comma operator works, we can tell that this code is equivalent to:

int a,b=5;
b++;
++b;
b*4; // nonsense, the result isn't stored anywhere
a=b-3;
printf("%d",a);

5 + 1 + 1 - 3 = 4. The b*4 part does nothing and is just obfuscation.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

comma acts both as a separator (in declaration of variables) and operator (evaluation of expressions).

In this case, comma acts as an operator. The comma operator introduces a sequence point between expressions.

The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

So your code is:

a = (b++, ++b, b*4, b-3);

Which is as if you had written this:

a = (5, 7, 28, 4);

So a is 4.

P.W
  • 26,289
  • 6
  • 39
  • 76
  • Thanks a lot for explaining both the usages. I was missing this and was having a really hard time trying to figure out what was happening. – crappyprog Dec 05 '18 at 10:46