Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Not understanding the output

Rohan Deshmkh
Ranch Hand
Posts: 127

I am not able to understand the above code . Why does it print 1?what does a=b do in above code?

jatan bhavsar
Ranch Hand
Posts: 299
• 1
hi Rohan,

In this code first assignment is evaluated which is a=b means value of array b is assigned to a but it will not change the value a its just evaluating.

Second thing is ((a = b)[3])) which means it will look for 4th element in array of a(which contains the value of b after evaluation).
At last it will a[(a = b)[3]] print 1 becuase it will print the 0th element from a.

Just seprate the brackets and you can see but make sure assignment is not done else it will change the value or array a.
Regards
jatan

R. Jain
Ranch Hand
Posts: 375
1
• 1
Rohan Deshmkh wrote:
I am not able to understand the above code . Why does it print 1?what does a=b do in above code?

(a = b) just makes both the reference a and b point to the same array (Initially pointed by b)
So,
a[(a = b)[3]] is translated to a[b[3]], which will print 1

R. Jain
Ranch Hand
Posts: 375
1
--

Rohan Deshmkh
Ranch Hand
Posts: 127
ok thanks i got it.
a[(a=b)[3]] is equivalent to a[b[3]].

R. Jain
Ranch Hand
Posts: 375
1
Rohan Deshmkh wrote:ok thanks i got it.
a[(a=b)[3]] is equivalent to a[b[3]].

But what here matters is how?? You should try to understand it..
You should probably make a diagram on paper with 2 boxes for array and a & b reference pointing to them..
And then see the change as yo proceed in the code.

Rohan Deshmkh
Ranch Hand
Posts: 127
yes i got it.Because of (a=b) ,a will point to the same array as that of b while evalulating (a=b)[3]

R. Jain
Ranch Hand
Posts: 375
1
Rohan Deshmkh wrote:yes i got it.Because of (a=b) ,a will point to the same array as that of b while evalulating (a=b)[3]

Also after the evaluation... try to print a[0] after this print statement..

Rohan Deshmkh
Ranch Hand
Posts: 127
a[0] will print 2 because a now refers to b array and b[0] is 2.

Bill Clar
Ranch Hand
Posts: 163
R. Jain wrote:
a[(a = b)[3]] is translated to a[b[3]], which will print 1

Why wouldn't it translate to b[b[3]]? Doesn't the assignment evaluate first?

Campbell Ritchie
Sheriff
Posts: 50699
83
Bill Clar wrote: . . . Doesn't the assignment evaluate first?
Probably yes, because it is in ().