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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With