1

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?

Aemmel
  • 122
  • 2
  • 6
  • 1
    Change `i1 < i2 ? i3 : i4 += 3;` to `i1 < i2 ? i3 += 3 : i4 += 3;`. However this is not really the use case for the conditional operator. – drescherjm Mar 06 '18 at 23:09
  • 2
    You seem to have forgotten to initialize `i1` and `i2` which makes everything UB. – nwp Mar 06 '18 at 23:09
  • @dreschrjim, I know it's not the use for it, and the code isn't very pretty in my opinion. I just wanted to try IF it works. And I still don't understand why my code doesn't work. – Aemmel Mar 06 '18 at 23:11
  • 1
    `int i1, i2, i3 = 0, i4 = 5;` Doesn't mean `i1` and `i2` are initialized to 0. – Raindrop7 Mar 06 '18 at 23:12
  • @Raindrop7 `i1` and `i2` will be initialized to 0 if they are global variables. – MikeCAT Mar 06 '18 at 23:12
  • @nwp, They are in my program. I just truncated that part to make the code more readible. In the text later I specifically write how i initialized them.... – Aemmel Mar 06 '18 at 23:12
  • Could you maybe add that somewhere? In the text later you only assign to `i3` and `i4`, never to `i1` or `i2`. It's very distracting when you are trained to spot uninitialized variables. – nwp Mar 06 '18 at 23:21
  • I wrote "When I set i1 > i2". But doesn't really matter, because it was already answered.. – Aemmel Mar 06 '18 at 23:24
  • You can check out this Q/A on c++ ternary operator: https://stackoverflow.com/questions/392932/how-do-i-use-the-conditional-operator – Francis Cugler Mar 07 '18 at 01:49

0 Answers0