tags:

views:

225

answers:

3
+3  Q: 

reference variable

In some text it is given that we can't assign constant values to a reference variable. When I executed such a program I could do it. Is there any condition we can't assign a constant value to a reference variable?

+1  A: 

You cannot assign a constant value to a non-constant reference, the same way you could not assign a constant value's address to a pointer pointing to a non-constant value.

At least, not without a const_cast.

Edit: If you were actually referring to literal values, Luc's answer is the better one. I was referring to const variables, not literals.

DevSolar
+8  A: 

You can initialize a constant reference to a constant value.

const int &i = 12;

If the reference is not const, you get a compiler error.

int &i = 12; //compiler error

Constant values (e.g. literals) are (most of the time) stored in read-only segments of the memory. Consequently, you can't reference them using non-const references, because that would mean you could modify them.

Luc Touraille
neither of those are assignments - they are both initialisations
anon
+1  A: 

You may be a bit confused regarding the difference between "initialisation" and "assignment". These are different in C++ and understanding the difference is crucial to understanding the language. Ignoring references:

int x = 1;    // initialisation
x = 1;        // assignment

References can only be initialised

int & r = x;  // initialisation
r = 2;        // assigns 2 to x _not_ to r

There is no way of re-initialising a reference.

Regarding your question, as far as consts are concerned, you can initialise const reference with a const value:

const int & r2 = 42;
anon