double & val = 66.6; //illegal
const double & val = 66.6; //legal
I was just doing some demo programs and came through the above concept but not able to identify what exactly the need of the above concept . what magic exactly const is doing in the second case ?
can anyone please let me know where exactly we can use this concept in real time programming

Recommended Answers

All 3 Replies

what magic exactly const is doing in the second case ?

I think a better question is how would having a non-const reference to a literal value work? A non-const reference basically says "I'm referring to an object with an address whose value can be modified". A literal value is neither of those: it doesn't exist as an object with an address, nor can it be modified. Therefore it makes sense that referencing a literal with a non-const reference is illegal.

int nVar = 12;
int &rVar = nVar ;//Ok
double &dVar = nVar ;//Error
const double &cdVar = nVar ;//Ok

can youplease explain Why the 3rd statement is not working where as 4th statement is working ?

nVar is converted to a double which results in a temporary variable which is an rvalue. A quick search for rvalues and lvalues yields the following definition:

You can think of an lvalue as an object that has a name. All variables, including nonmodifiable (const) variables, are lvalues. An rvalue is a temporary value that does not persist beyond the expression that uses it.

A better source of reading is this.

You may not associate a temporary variable with a reference, but you may with a const reference. (The last extends the lifetime of the temporary variable)

Would link a section of the specification, but seems to troublesome to go through that :<. Should look into it yourself though, it'll be in there.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.