Friday 5 April 2013

What is the difference between const char *p, char * const p and const char * const p?


What is the difference between const char *p, char * const p and const char * const p?

The basic rule of thumb with const (and volatile) keyword is that it applies to whatever is immediately to its left. If there is nothing to its left, it applies to whatever is immediately to its right. By this logic, "const char *" is a (non-const) pointer to a const char, and "char const *" means the same thing.

1. const char *p : means p is pointer pointing to a constant char i.e. you can not change the content of the location where it is pointing but u can change the pointer itself to point to some other char. 

2. char const *p, and char * const p : both are same & in this case p is a constant pointer poiting to some char location. you can change the contents of that location but u can't change the pointer to point to some other location.

const char *p - This is a pointer to a constant character. You cannot change the value pointed by p, but you can change the pointer p itself.

*p = 'S' is illegal.
p = "Test" is legal.

Note - char const *p is the same.


const * char p - This is a constant pointer to non-constant character. You cannot change the pointer p, but can change the value pointed by p.

*p = 'A' is legal.
p = "Hello" is illegal.


const char * const p - This is a constant pointer to constant character. You cannot change the value pointed by p nor the pointer p.

*p = 'A' is illegal.
p = "Hello" is also illegal. 

No comments:

Post a Comment