Const keyword in C++ is a simple concept. A variable declared with ‘const’,  becomes constant and cannot be changed.  For example “const int xhr = 49” , the variable xhr is constant.

const keyword in c++ basic

The const keyword sometime becomes messy and it becomes a little difficult to say what is constant and what is non const. For example try to find what is constant in expression ” int const *p” or in “const int *p”.

Const keyword in C++ with examples

Pointer to constant

const int *xhr;

xhr is a pointer to a const int type. We can modify xhr  but the object pointed to by xhr shall not be modified.

#include<iostream>
using namespace std;

int x = 5;
const int *xhr;

int main()
{
  xhr = &x;
  *xhr = 8; // error
  return 0;
}
bosch@bosch-Inspiron-N5050:~$ g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:10:8: error: assignment of read-only location ‘* xhr’
*xhr = 8;
^

constant pointer

int * const ptr;

So here ptr is constant pointer and we cannot modify ptr. we can modify the object which is pointed by ptr.

#include<iostream>
using namespace std;

int x = 5;
int y = 6;
void foo() {

   int * const ptr = &x;
   // change the value at ptr
   *ptr = 6;
    ptr = &y; //error 
}

int main()
{
  return 0;
}

constant pointer to constant variable

const int * const ptr;

The declaration shows that neither ptr can be modified nor the variable at which it is pointing to.

#include<iostream>
using namespace std;

int x = 5;

void foo() {
   const int * const ptr = &x;
   *ptr = 6; // error
    ptr = &x; // error
}

int main()
{
  return 0;
}
bosch@bosch-Inspiron-N5050:~$ g++ test.cpp
test.cpp: In function ‘void foo()’:
test.cpp:8:9: error: assignment of read-only location ‘*(const int*)(& x)’
*ptr = 6; // error
^
test.cpp:9:9: error: assignment of read-only variable ‘ptr’
ptr = &x; // error

Interview questions related to const key word in c++

  • What is a const in C++?
  • What is the constant qualifier in C++?
  • What does a constant function in C++ mean?
  • What is a const variable?


Related Contents to follow