programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Two "=" in the same line .

Fox Hu
Ranch Hand
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
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
Posts: 49
Well I see .
Thank you .

Wang Yang
Greenhorn
Posts: 5
Such code cause compiler errors.