aspose file tools*
The moose likes Beginning Java and the fly likes Two Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Two "=" in the same line ." Watch "Two "=" in the same line ." New topic
Author

Two "=" in the same line .

Fox Hu
Ranch Hand

Joined: Jan 23, 2003
Posts: 49
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

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Jan 23, 2003
Posts: 49
Well I see .
Thank you .
Wang Yang
Greenhorn

Joined: Oct 11, 2002
Posts: 5
Such code cause compiler errors.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Two "=" in the same line .
 
Similar Threads
Arrays
Question on overloading..
overloading -> cannot have different return type?
DanChisholm's assertion question
Help needed.....