I was just learning about conditional operators in C++ and how they return an lvalue. So I tried using it, to determine what variable was to be changed. My code looks like this:
int i1, i2, i3 = 0, i4 = 5;
i1 < i2 ? i3 : i4 += 3;
//print i3 and i4 to see what happened
When I set i1 > i2
, then the code produced the expected result (i3 = 0, i4 = 8
). But when I set i1 < i2
, so that the condition was true (and i3 was supposed to be incremented by 3), nothing happened, i.e. i3 = 0, i4 = 5
.
I tried it with another compiler but same result.
As I understand it, the conditional operator has a higher precedence than the assignment operator, meaning that the expression above should automatically be grouped like this: (i1 < i2 ? i3 : i4) += 3
. But when I try it with this code (parentheses specifically written), everything works fine and the code doesn't "break" when the condition is met...
I have absolutely no clue to why this happens and it seems weird to me..
Can someone please enlighten me?