Monday 6 July 2009

Example of 'pointer to const' and 'const pointer'

Continuing with the const correctness theme:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example of pointer to const and const pointer
#include<iostream>

using namespace
std;

int
main()
{

//Lets look at const with pointers
int a = 34;
int
b = 2009;

int
*const x = &a; //COMPULSARY: const object must be initialized
cout<<"*x(1) = "<<*x<<endl;

*
x = 33;
cout<<"*x(2) = "<<*x<<endl;

//x = &b; - NOT POSSIBLE because x is const

const
int *y;
y = &b;
cout<<"*y(1) = "<<*y<<endl;

//*y = 2004; - NOT POSSIBLE
y = x; // POSSIBLE
cout<<"*y(2) = "<<*y<<endl;

int
c = 23456;
int
const *z=&c;
cout<<"*z(1) = "<<*z<<endl;
//*z = 77777; - NOT POSSIBLE, same as *y case
z = x; //POSSIBLE
cout<<"*z(2) = "<<*z<<endl;

//Now lets look const variables
const int i = 1111;
int
const j = 4444;
//i = 66; - NOT POSSIBLE
//j = 77; - NOT POSSIBLE, exactly same as i
//But we can manipulate i or j using pointers and const_cast
int *k = const_cast<int *>(&i);
cout<<"*k(1) = "<<*k<<endl;
*
k = 5678;
cout<<"*k(2) = "<<*k<<endl;
cout<<"i = "<<i<<endl; //Should be 5678 but output maybe 1111
//Change i to const volatile int i = 1111; to get the desired result

return
0;
}


The output is as follows:

It may be sometimes confusing to remember is the const is associated with the pointer or the variable. A simpler way to remember is that const is applied to whatever it is near. Another thing is that You have to read pointer declarations right-to-left. So:

  • const Fred* p means "p points to a Fred that is const" — that is, the Fred object can't be changed via p.
  • Fred* const p means "p is a const pointer to a Fred" — that is, you can change the Fred object via p, but you can't change the pointer p itself.
  • const Fred* const p means "p is a const pointer to a const Fred" — that is, you can't change the pointer p itself, nor can you change the Fred object via p.

No comments:

Post a Comment