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

Time:01-03

#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.

CodePudding user response:

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)

CodePudding user response:

This is an example of the comma operator in C, not to be confused with commas used in argument lists.

The comma operator first evaluates its left operand for side effects (throwing away the resulting value), and then evaluates its right operand. All side effects in that left operand will be sequenced-before all side effects and reads in the right operand.

So g will increment g, and then g wil increment g again and give the value after this second increment.

CodePudding user response:

g will increment g after ;

No, it will increment g before g. , is a sequence operator. See the example here.

  • Related