Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why double reference value doesn't change when assigned to float variable in C++

Tags:

c++

reference

I am trying to understand the concept of assigning a float to const reference double and the value of double doesn't change if the float value updated.

float d = 2.0;
const double & f = d;
d = 3.0;
std::cout << d << " " << f << std::endl;

output:

 3 2

What is the reason behind this.

However this issue is not seen when we set the reference variable as the same type as the other variable.

like image 633
Shaju Paul Avatar asked Jan 27 '23 19:01

Shaju Paul


1 Answers

However this issue is not seen when we set the reference variable as the same type as the other variable

That's the point; you can't bind reference to object with different type directly.

Given const double & f = d;, a temporary double will be constructed from d, then bound to the reference f. The modification on d has nothing to do with the temporary; they're two irrelevant objects. That's why you got different result when print out d and f.

BTW: Only the lvalue reference to const and rvalue reference could be bound to temporary, so const double & f = d; and double && f = d; work fine. Lvalue reference to non-const can't be bound to temporary, then double & f = d; won't work.

like image 186
songyuanyao Avatar answered Jan 30 '23 08:01

songyuanyao