Difference between const char *p, char const *p and char *const p

Difference between const char *p, char const *p and char *const p

Difference between const char *p, char const *p and char *const p is most confusing interview question ever faced by c developer or candidate including me. So i have find the answer of this question some how and want to publish as a article to share my knowledge.

 

Answer:-

First two const char *p and char const *p both are same i.e. points to constant character(You can change where p points, but you can’t change pointed characters using that pointer).

 

But char * const p is a constant pointer to a variable(i.e. you can’t change the pointer).

 

There is also const char * const p which is a constant pointer to a constant char (so nothing about it can be changed).

This answer is enough to find difference between these three statements, but not sufficient to build your fundamental concept until you used it practically.

So, let we understand it with example

1). const char  *p (Points to constant character)

 

2). char *  const  p (Constant pointer to variable)

 

 3). const  char  *  const  p (Constant pointer to a constant char)

 

Summary

const char *p                  = Can’t change pointed characters using pointer, can change pointer

char const *p                  = Can’t change pointed characters using pointer, can change pointer

char * const p                 = Address cannot be changed, Must be initialize at declaration time

const char * const p      = Both address and value cannot be changed, Initialized at declaration time

 

Trick or Tips

Another thumb rule is to check where const is:

    before *           => Can’t change pointed characters using pointer

    after *              => Can’t change pointer stored address