Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of a constant reference with a number [duplicate]

What is the meaning of the following line? Why is this allowed as 0 is an r-value and not a variable name? What is the significance of const in this statement?

const int &x = 0; 
like image 684
user3112666 Avatar asked May 15 '18 21:05

user3112666


People also ask

How do you initialize a reference variable?

If an rvalue reference or a nonvolatile const lvalue reference r to type T is to be initialized by the expression e , and T is reference-compatible with U , reference r can be initialized by expression e and bound directly to e or a base class subobject of e unless T is an inaccessible or ambiguous base class of U .

Why can't you make a non const reference to a literal?

A non-const reference cannot point to a literal. You cannot bind a literal to a reference to non-const (because modifying the value of a literal is not an operation that makes sense) and only l-values can be bound to references to non-const.

How do you reference a constant?

A constant reference is an expression that evaluates to the value of the named constant. The simplest constant references are primary expressions—they consist simply of the name of the constant: CM_PER_INCH = 2.54 # Define a constant. CM_PER_INCH # Refer to the constant.

Do constant variables need to be initialized?

A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .


1 Answers

A non-const reference cannot point to a literal. You cannot bind a literal to a reference to non-const (because modifying the value of a literal is not an operation that makes sense) and only l-values can be bound to references to non-const. You can however bind a literal to a reference to const.

The "const" is important. In this case, a temporary variable is created for this purpose and it's usually created on stack.

like image 146
user3112666 Avatar answered Oct 13 '22 21:10

user3112666