-1

I have the following expression in C. I'm asked whether we can predict the value of z

int x,y,z;
z= (x=2) + (y=x)

I know that the () operator has left associativity. Does this mean that the left parenthesis will be evaluated before the ones on the right?

I'm trying to understand if I got this concept correctly

Thanks in advance

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219

1 Answers1

0

No. Associativity says that x + (y + z) == (x + y) + z == x + y + z; the parentheses don't matter when chaining 2 or more of the same operator.

In your code, the compiler is free to evaluate the operands of + in either order. You don't know if the result will be

x=2; y=x; z = x + y;

or

y=x; x = 2; z + x + y;
chepner
  • 497,756
  • 71
  • 530
  • 681
  • But that's the associativity of the addition, not the parentheses, isn't it? – Francisco José Letterio Mar 09 '18 at 20:04
  • No, parentheses aren't operators. They group expressions to modify *precedence*, since `z = x = 2 + y = x` would otherwise be parsed as ... I'm not even sure off the top of my head. Maybe `z = (x = (2 + (y = x)))`? – chepner Mar 09 '18 at 20:08