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;
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 .
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With