Const keyword

Const keyword

In C++, the const keyword is used to indicate that a variable, pointer, reference, or function cannot be modified.

When used with a variable, const makes the variable read-only, meaning that its value cannot be changed after it has been initialized. For example:

const int x = 5;
x = 6; // Error: assignment of read-only variable 'x'

When used with a pointer, const indicates that the value pointed to by the pointer cannot be modified, but the pointer itself can be changed to point to a different memory location. This is indicated by const appearing to the right of the *. For example:

int x = 5;
const int* ptr = &x;
*ptr = 6; // Error: assignment of read-only location '*ptr'
ptr = nullptr; // ok, changes the value of ptr to null

When used with a pointer, const appearing to the left of the * indicates that the pointer itself is constant, but the value it points to can be changed. For example:

int x = 5;
int y = 10;
int* const ptr = &x;
*ptr = 6; // ok, changes the value of x
ptr = &y; // Error: cannot assign to variable 'ptr' with const-qualified type 'int *const'

When used with a reference, const indicates that the reference cannot be used to modify the object it refers to. For example: