Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Right Associativity doesn't work with the declaration statement

Tags:

c

int a=b=c=10;  //invalid statement

But following are valid statements

int a,b,c;
a=b=c=10;

First one is invalid as b assigned to a even before b got its value.

But the second case is valid as equal(=) sign is having right associative i.e "=" sign will start getting preference from the right side.

My question is: why doesn't Right Associativity apply in the first case? Does it mean that Associativity doesn't work with the declaration statement? I need more clarity on this.

like image 631
Joe Avatar asked Aug 22 '10 17:08

Joe


2 Answers

It doesn't work because it isn't syntactically correct. As you show in the second example, more than one variable of a type are declared using commas as a separator. If instead b and c are already declared then things work fine. For example this works:

int b,c;
int a=b=c=10;

You can even do this (at least with VS2010 compiler):

int b,c,a=b=c=10;

Mind you I'd say that looks BAD, and advise against it.

like image 70
torak Avatar answered Nov 11 '22 04:11

torak


If it'd be not just an exercise but you had tested this with a real compiler, you probably would have given us a bit more information of actually what displeases the compiler.

Part of the answer would be to notice the two different roles of the = operator. One is assignment and one is initialization. Your example

int a = b = c = 10;

is equivalent to

int a = (b = (c = 10));

So the two = on the right are assignments and not initializations. And in an assignment the left hand side must be well defined.

like image 35
Jens Gustedt Avatar answered Nov 11 '22 05:11

Jens Gustedt