Pointers and Const in C/C++

October 5th, 2009 Leave a Comment

A quick run here. The combination of pointers and const came to my mind and I thought of sharing them with you today. It is also often asked in the interview questions, particularly in the C/C++ programming topic.

The const keyword and pointers are not new to C++. They have been always been used in C. However, things can be a bit tricky when pointers are combined with const. Consider the following declarations:

int * p1;
const int * p2;
int * const p3;
const int * const p4;
int const * p5;

The first and second lines are the ones which we normally use in our day-to-day programming tasks, at least for me. So, let’s get straight into it.

  • p1 is a non-const pointer to non-const integer, which means you can modify either pointer or the integer pointed to by it freely.
  • p2 is a non-const pointer to const integers. You can modify the pointer but not the integer it is pointing to.
  • p3 has a const immediately to the left of the pointer variable, so the pointer is a const, but not the integer it points to.
  • p4 is the opposite of p1; you cannot modify either the pointer or the integer pointed to by it.
  • p5 is non-const pointer to const integer; it has the same effect as p2.

I hope it helps :)

Tags:
, , ,

Leave a Reply


five × 5 =