Using ternary operator to initialize a reference variable?

前端 未结 2 912
无人共我
无人共我 2021-02-12 21:52

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         


        
2条回答
  •  清歌不尽
    2021-02-12 22:49

    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
    

提交回复
热议问题