# Two "=" in the same line .

Fox Hu

Ranch Hand

Posts: 49

Anonymous

Ranch Hand

Posts: 18944

posted 12 years ago

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

- 0

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

I agree. Here's the link: http://aspose.com/file-tools |