[c++] What is a constant reference? (not a reference to a constant)

A pretty theoretical question...Why constant references do not behave the same way as constant pointers and I can actually change the object they are pointing to? They really seem like another plain variable declaration. Why would I ever use them? This is a short example that I run which compiles and runs with no errors:

int main (){
    int i=0;
    int y=1;    
    int&const icr=i;
    icr=y;          // Can change the object it is pointing to so it's not like a const pointer...
    icr=99;         // Can assign another value but the value is not assigned to y...
    int x=9;
    icr=x;
    cout<<"icr: "<<icr<<", y:"<<y<<endl; 
}

This question is related to c++ reference constants

The answer is


This code is ill-formed:

int&const icr=i;

Reference: C++17 [dcl.ref]/1:

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name or decltype-specifier, in which case the cv-qualifiers are ignored.

This rule has been present in all standardized versions of C++. Because the code is ill-formed:

  • you should not use it, and
  • there is no associated behaviour.

The compiler should reject the program; and if it doesn't, the executable's behaviour is completely undefined.

NB: Not sure how none of the other answers mentioned this yet... nobody's got access to a compiler?


The statement icr=y; does not make the reference refer to y; it assigns the value of y to the variable that icr refers to, i.

References are inherently const, that is you can't change what they refer to. There are 'const references' which are really 'references to const', that is you can't change the value of the object they refer to. They are declared const int& or int const& rather than int& const though.


As it mentioned in another answers, a reference is inherently const.

int &ref = obj;

Once you initialized a reference with an object, you can't unbound this reference with its object it refers to. A reference works just like an alias.

When you declare a const reference, it is nothing but a reference which refers to a const object.

const int &ref = obj;

The declarative sentences above like const and int is determining the available features of the object which will be referenced by the reference. To be more clear, I want to show you the pointer equivalent of a const reference;

const int *const ptr = &obj;

So the above line of code is equivalent to a const reference in its working way. Additionally, there is a one last point which I want to mention;

A reference must be initialized only with an object

So when you do this, you are going to get an error;

int  &r = 0; // Error: a nonconst reference cannot be initialized to a literal

This rule has one exception. If the reference is declared as const, then you can initialize it with literals as well;

const int  &r = 0; // a valid approach

First I think int&const icr=i; is just int& icr = i, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).

const int x = 10;
// int& const y = x; // Compiler error here

Second, constant reference just means you cannot change the value of variable through reference.

const int x = 10;
const int& y = x;
//y = 20; // Compiler error here

Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.

float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340

By "constant reference" I am guessing you really mean "reference to constant data". Pointers on the other hand, can be a constant pointer (the pointer itself is constant, not the data it points to), a pointer to constant data, or both.


What is a constant reference (not a reference to a constant)
A Constant Reference is actually a Reference to a Constant.

A constant reference/ Reference to a constant is denoted by:

int const &i = j; //or Alternatively
const int &i = j;
i = 1;            //Compilation Error

It basically means, you cannot modify the value of type object to which the Reference Refers.
For Example:
Trying to modify value(assign 1) of variable j through const reference, i will results in error:

assignment of read-only reference ā€˜iā€™


icr=y;          // Can change the object it is pointing to so it's not like a const pointer...
icr=99;

Doesn't change the reference, it assigns the value of the type to which the reference refers. References cannot be made to refer any other variable than the one they are bound to at Initialization.

First statement assigns the value y to i
Second statement assigns the value 99 to i


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to reference

Method Call Chaining; returning a pointer vs a reference? When to create variables (memory management) Reference to non-static member function must be called Cannot find reference 'xxx' in __init__.py - Python / Pycharm c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration) C++ initial value of reference to non-const must be an lvalue Dependent DLL is not getting copied to the build output folder in Visual Studio How to write to error log file in PHP How to reference Microsoft.Office.Interop.Excel dll? Linker Error C++ "undefined reference "

Examples related to constants

Constants in Kotlin -- what's a recommended way to create them? Why Is `Export Default Const` invalid? Proper use of const for defining functions in JavaScript Declaring static constants in ES6 classes? How can I get the size of an std::vector as an int? invalid use of non-static member function Why does JSHint throw a warning if I am using const? Differences Between vbLf, vbCrLf & vbCr Constants Constant pointer vs Pointer to constant Const in JavaScript: when to use it and is it necessary?