19

Putting all the maintainability and reading issues aside, can these lines of code generate undefined behavior?

float  a = 0, b = 0;
float& x = some_condition()? a : b;
x = 5;
cout << a << ", " << b;
Ravindra S
  • 6,302
  • 12
  • 70
  • 108
Ali1S232
  • 3,373
  • 2
  • 27
  • 46

2 Answers2

13

No, it's just fine. It would not create undefined behavior in this code. You will just change value of a or b to 5, according to condition.

Blood
  • 4,126
  • 3
  • 27
  • 37
9

This is absolutely fine, as long as both sides of the conditional are expressions that can be used to initialize a reference (e.g. variables, pointer dereferences, etc)

float& x = some_condition()? a : *(&b); // This is OK - it is the same as your code
float& x = some_condition()? a : b+1;   // This will not compile, because you cannot take reference of b+1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523