使用三元运算符初始化引用变量

Using ternary operator to initialize a reference variable?

本文关键字:运算符 初始化 引用 变量 三元      更新时间:2023-10-16

抛开所有的可维护性和读取问题不谈,这些代码行能产生未定义的行为吗?

float  a = 0, b = 0;
float& x = some_condition()? a : b;
x = 5;
cout << a << ", " << b;

不,没关系。它不会在此代码中创建未定义的行为。您只需根据条件将a或b的值更改为5即可。

只要条件的两边都是可用于初始化引用(例如变量、指针取消引用等)的表达式,这是绝对可以的。

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