Const

const is a qualifier which, applied to a variable, makes such a variable impossible to be changed by the program where it is declared:

const int j = 21;
// j = 12; // ERRROR!
const can also be used to protect formal parameters from being modified by the function’s code:

int i = 5; // global

void printCube(const int x) // x is a formal parameter
{
     //x = 5; ERROR!
     cout << x << "\'s square is: " << x*x*x;
}
}
also, in case the parameter is a pointer, the object pointed to cannot be modified either:

void f(const int *p)
{
     // *p = 1; ERROR!
}
Notice that const applies only to the program containing the variable declaration. An external entity might still be able to modify the memory locations where a const object is stored.

Example


#include <iostream>
using namespace std;

void printCube(const int x) // x is a const formal parameter
{
      //x = 5; ERROR!
     cout << x << "\'s square is: " << x*x*x;
}

void f(const int *p)
{
     // *p = 1; ERROR!
}

int main()
{   
     const int j = 21;
     // j = 12; // ERRROR!
     printCube(7);
}

Output

7's square is: 343