1
#include<stdio.h>
#include<stdlib.h>
int main() {

    int x  = 5;
    int y = 0;
    x++, y = x*x;
    printf("x is %d\n", x);
    printf("y is %d\n", y);

}

Question: Why the output of the above code is:

x is 6
y is 36

instead of

x is 6
y is 25

?

Reasoning: I am thinking it should be the latter because assignment operator has higher precedence than comma and therefore first an assignment to y should happen setting it to 25 and then x should be evaluated and set to 6.

Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208

3 Answers3

3

The LHS of the comma operator has to be evaluated before the RHS of the comma operator; there is a full sequence point between the two.

Therefore, x++ has to be evaluated and all side-effects (the increment) must take place before the y = x * x part of the expression is considered or any part of it evaluated.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
3

Precedence has to do with the syntax tree of your program, not with how the program executes. What those precedence levels are doing is disambiguating between

x++, (y = x*x) /* this is how your programs gets parsed */

and

(x++ ,  y) = x*x  /* this is NOT how it is parsed */

After your program gets parsed, the execution rules for , state that expressions are evaluated from left to right so the x++ gets run before the y = x*x. In the end, the , is very similar to a ;, except that you can put it inside places that expect expressions instead of statements.

Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208
hugomg
  • 68,213
  • 24
  • 160
  • 246
1

The precedence doesn't determine the order of evaluation. = binds highly than , so the expression is:

(x++), ( y = x*x;)

Comma is evaluated left to right and includes a sequence point so your expression is similar to:

x++ ; y = x*x ;
this
  • 5,229
  • 1
  • 22
  • 51