Constant Pointer And Pointer To A Constant

The keyword const specifies that you can not change the value of the variable. When it comes to pointers, we can have two types of constants.

Constant Pointer

It prevents you from changing the pointer from one memory location to another. However, you can change the contents of the pointer.

   int myInt = 10;
   int* const pInt = &myInt;  // Constant pointer
   int myNewInt = 20;
   pInt = &myNewInt; //Illegal 
   *pInt = 30; // Legal

Pointer to a constant

It prevents you from changing the contents of the memory location. However, you can reassign the pointer to a new memory location.

   int myInt = 10;
   const int* pInt = &myInt;  // Pointer to a constant
   int myNewInt = 20;
   pInt = &myNewInt; //Legal 
   *pInt = 30; // Illegal
Advertisements

2 Responses to Constant Pointer And Pointer To A Constant

  1. ItsJustMe says:

    Cool stuff..

  2. […] *const – This is a constant pointer. The pointer itself is constant, though in theory the actual value underlying the pointer could change at a later date. If we were to use a pointer to a constant (e.g., const NSString *) the memory contents could not change, but the pointer could be moved around. You can read more about this at cppkid. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: