Search code examples
c++operator-precedence

Operator precedence C++


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?


Solution

  • 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.