What\'s the difference between:
char * const
and
const char *
const * char
is invalid C code and is meaningless. Perhaps you meant to ask the difference between a const char *
and a char const *
, or possibly the difference between a const char *
and a char * const
?
char * const and const char *?
const char * p;
// value cannot be changed
char * const p;
// address cannot be changed
const char * const p;
// both cannot be changed.
I would like to point out that using int const *
(or const int *
) isn't about a pointer pointing to a const int
variable, but that this variable is const
for this specific pointer.
For example:
int var = 10;
int const * _p = &var;
The code above compiles perfectly fine. _p
points to a const
variable, although var
itself isn't constant.
const char* x Here X is basically a character pointer which is pointing to a constant value
char* const x is refer to character pointer which is constant, but the location it is pointing can be change.
const char* const x is combination to 1 and 2, means it is a constant character pointer which is pointing to constant value.
const *char x will cause a compiler error. it can not be declared.
char const * x is equal to point 1.
the rule of thumb is if const is with var name then the pointer will be constant but the pointing location can be changed , else pointer will point to a constant location and pointer can point to another location but the pointing location content can not be change.
Here is a detailed explanation with code
/*const char * p;
char * const p;
const char * const p;*/ // these are the three conditions,
// const char *p;const char * const p; pointer value cannot be changed
// char * const p; pointer address cannot be changed
// const char * const p; both cannot be changed.
#include<stdio.h>
/*int main()
{
const char * p; // value cannot be changed
char z;
//*p = 'c'; // this will not work
p = &z;
printf(" %c\n",*p);
return 0;
}*/
/*int main()
{
char * const p; // address cannot be changed
char z;
*p = 'c';
//p = &z; // this will not work
printf(" %c\n",*p);
return 0;
}*/
/*int main()
{
const char * const p; // both address and value cannot be changed
char z;
*p = 'c'; // this will not work
p = &z; // this will not work
printf(" %c\n",*p);
return 0;
}*/
Another thumb rule is to check where const is: