What Is The Difference Between Const*char And Const Char*?

2

2 Answers

Naeem Sheeraz Profile
Naeem Sheeraz answered
There is not a "const * char". It won't compile. I guess what you meant is "char * const", versus "const char *".

They are completely different.

char * const p1;

declares a constant pointer through which you can have both read and write access to a char. But the pointer itself is a constant and you can NOT change it. Like all other constant variables, you must initialize it with a constant value at the same time when it is declared. You are not allowed to set it later in the code.

const char * p2;

declares a pointer through which you may be able to access a char but you can not change it through the said pointer. But the pointer itself can be changed.

Please note, there is a myth that a lot of people, including some with several decades of programming experience, think that "const char *" means a pointer to a constant char. That is totally wrong. "const char *" only means that the char can not be modified using the pointer. It may well be a regular, changeable char, changeable through other means or other pointers. It is just that the compiler would NOT allow you to change that char direction through the const char pointer.

A real const char is not changeable at all, no matter how you try. A real const char may either be put in read-only memory so it is simply physically impossible to change it at run time. Or it may be allocated no storage space at all and be used directly in place where ever the said const char is referenced. In this later case there is certainly no way a pointer can be derived to point to the char at all, since it doesn't occupy any storage space.

So keep in mind, "const char *" is NOT "a pointer to a constant char".

What about "const char[]". That is different than "const char*". In the case "const char[]", it defines a constant char array and the same variable name refers to both the array, and a pointer to the beginning of the array. It is indeed constant in this case.
John Peter Profile
John Peter answered
Const char * variable_name
declares a pointer to a constant character. We cannot use this pointer to change the value that is being pointed.

Const* char variable_name
we cannot declare any constant pointer like this.

Answer Question

Anonymous