Control variable

Some text indicates that we cannot assign constant values ​​to a reference variable. When I executed such a program, I was able to do it. Is there any condition that we cannot assign a constant value to a reference variable?

+4
source share
3 answers

You can initialize a permalink to a constant value.

const int &i = 12; 

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

 int &i = 12; //compiler error 

Constant values ​​(e.g. literals) (in most cases) are stored in read-only memory segments. Therefore, you cannot link to them using non-constant links, because that means you can change them.

+10
source

You cannot assign a constant value to a link without a constant, just as you cannot assign a constant address of a value to a pointer that points to a non-constant value.

At least not without const_cast.

Edit: If you really referenced literal values, Luc's answer is better. I was referring to constant variables, not literals.

+1
source

You may be a little confused about the difference between “initialization” and “assignment”. In C ++, they are different, and understanding the difference is critical to understanding the language. Ignoring Links:

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

Links can only be initialized.

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

There is no way to reinitialize a link.

Regarding your question, regarding consts, you can initialize the constant const with a value of const:

 const int & r2 = 42; 
+1
source

All Articles