Reputation:
What operator precedence takes place in the following C++ statement?
int lower = height[height[l] < height[r] ? l++ : r--];
Assume, height=[0,1,0,2,1,0,1,3,2,1,2,1]
and int l = 0, r = height.size()-1;
.
As per my understanding, height[l] < height[r]?
would be evaluated first, followed by l++
or r--
as the case might be (l++
in this case). Then the value of height[updated l]
should be assigned to lower
. Thus lower
should be 1
; but the output says it is 0
. How? What would be the correct order of the evaluation of the statements then?
Upvotes: 1
Views: 182
Reputation: 4189
The code is equal to:
int lower = height[height[l] < height[r] ? l : r];
(height[l] < height[r]) ? l+=1 : r-=1;
Upvotes: -1
Reputation: 28499
The l++
uses the post-increment operator. The value of l is increased after the value of the expression is evaluated. So, when l is 0, the value of l++
is 0 and not 1, even though the variable l will have the value 1 afterwards.
Using ++l
would show a different behaviour.
The following statement in the question is incorrect:
Then the value of height[updated l] should be assigned to lower
The updated value of l is not used as the array index, but the value of the expression l++
, which is the value of l before it is increased.
Upvotes: 3
Reputation: 33864
l++
is the post increment operator, which means it will be incremented after the operation is complete. Hence the output 0
, everything else is correct.
Upvotes: 1