ccomma-operator

What would be the output obtained out of the program and how?


#include<stdio.h>

void main() {

    int g = 83;

    int h = (g++, ++g);

    printf(“%d”, h);

}

**g++** will increment **g** after **;**

My answer: h = 84

Correct answer: h = 85

I am a beginner that's why I am confused.


Solution

  • We first evaluate the left operand g++ so g is now 84 but otherwise ignore the result. Then we evaluate the right operand ++g so g is now 85.

    Here is the relevant sections of the specification:

    The presence of a sequence point between the evaluation of expressions A and B implies that every value computation and side effect associated with A is sequenced before every value computation and side effect associated with B. (5.1.2.3)

    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. (6.5.17)