Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Two "=" in the same line .

 
Fox Hu
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int a=0;
int b[] = new int[5];
int c=3;
b[a]=a=c; //a=b[a]=c;
Both "b[a]=a=c;" and "a=b[a]=c;" has the same result .
But I want to know the reason .
How does it work ?
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Neal Hanson:
int a=0;
int b[] = new int[5];
int c=3;
b[a]=a=c; //a=b[a]=c;
Both "b[a]=a=c;" and "a=b[a]=c;" has the same result .
But I want to know the reason .
How does it work ?

Ok, step by step; the assignment operator (=) is a right associative operator, i.e. the expressions above are evaluated from right to left. The one little trick that might have caused some confusion is that the subexpression 'b[a]' is evaluated first, i.e. this subexpression denotes the zeroth elemt of array b (b[0]).
The first double assignment expression evaluates as follows:
b[a]= a= c; / b[0]= 0, a= 0, c= 3;
b[a]= (a= c); / b[0]= 0, a= 3, c= 3;
(b[a]= 3); / b[0]= 3, a= 3, c= 3;
The second double assignment expression evaluates as follows:
a= b[a]= c; / a= 0, b[0]= 0, c= 3;
a= (b[a]= c); / a= 0, b[0]= 3, c= 3;
(a= 3); / a= 3, b[0]= 3, c= 3;
And indeed, both assignment expressions have identical results.
kind regards
 
Fox Hu
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well I see .
Thank you .
 
Wang Yang
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Such code cause compiler errors.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic