Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ternary operator to initialize a reference variable?

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;
like image 444
Ali1S232 Avatar asked Jul 15 '12 19:07

Ali1S232


People also ask

How do you initialize a reference variable?

There are three steps to initializing a reference variable from scratch: declaring the reference variable; using the new operator to build an object and create a reference to the object; and. storing the reference in the variable.

How do you initialize a reference variable in a class C++?

An rvalue reference can be initialized with an lvalue in the following contexts: A function lvalue. A temporary converted from an lvalue. An rvalue result of a conversion function for an lvalue object that is of a class type.

How do you initialize const and reference member variables?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.


1 Answers

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.

like image 141
Blood Avatar answered Oct 08 '22 06:10

Blood