Difference between const char* p and char const* p
Difference between "const char* p" and "char const* p" in Programming
In C programming, both const char* p and char const* p declare a pointer p to a constant character string. However, there is a subtle difference in the meaning of these two declarations.
const char* p: In const char* p, the character pointed by ‘p’ is constant, so u cant change the value of the character pointed by p but u can make ‘p’ refer to some other location.
char const* p: in char const* p, the ptr ‘p’ is constant not the character referenced by it, so u cant make ‘p’ to refer to any other location but u can change the value of the char pointed by ‘p
const char* p means that the data pointed to by p is constant, i.e., the characters in the string cannot be modified through the pointer p. However, the pointer p itself is not constant and can be reassigned to point to a different memory location.
On the other hand, char const* p means that the pointer p is constant and cannot be reassigned to point to a different memory location. However, the data pointed to by p can be modified.
So, in summary:
- const char* p: pointer to a constant character string. The data pointed to by p is constant and cannot be modified through p, but p itself can be reassigned to a different memory location.
- char const* p: constant pointer to a character string. The data pointed to by p can be modified, but p itself is constant and cannot be reassigned.
It's worth noting that the two declarations are equivalent, as const can appear either before or after the type that it modifies.