Home >Backend Development >C++ >Difference between const char*p, char*const p and const char*const p in C
In the C programming language, *p represents the value stored in the pointer, and p represents the address of the value, which is called a pointer.
const char* and char const* indicate that the pointer can point to a constant character, and the value of the character pointed to by the pointer cannot be changed. But we can change the value of the pointer because it is not a constant and can point to another constant character.
char* const means that the pointer can point to a character, and the value of the character pointed to by the pointer can be changed. But we cannot change the value of the pointer because it is now a constant and cannot point to another character.
const char* const means that the pointer can point to a constant character, and the value of the character pointed to by the pointer cannot be changed. We also cannot change the value of the pointer because it is now a constant and cannot point to another constant character.
The principle of naming syntax is from right to left.
// constant pointer to constant char const char * const // constant pointer to char char * const // pointer to constant char const char *
Uncomment the erroneous code and view the error.
Real-time demonstration
#include <stdio.h> int main() { //Example: char const* //Note: char const* is same as const char* const char p = 'A'; // q is a pointer to const char char const* q = &p; //Invalid asssignment // value of p cannot be changed // error: assignment of read-only location '*q' //*q = 'B'; const char r = 'C'; //q can point to another const char q = &r; printf("%c</p><p>", *q); //Example: char* const char u = 'D'; char * const t = &u; //You can change the value *t = 'E'; printf("%c", *t); // Invalid asssignment // t cannot be changed // error: assignment of read-only variable 't' //t = &r; //Example: char const* const char const* const s = &p; // Invalid asssignment // value of s cannot be changed // error: assignment of read-only location '*s' // *s = 'D'; // Invalid asssignment // s cannot be changed // error: assignment of read-only variable 's' // s = &r; return 0; }
C E
The above is the detailed content of Difference between const char*p, char*const p and const char*const p in C. For more information, please follow other related articles on the PHP Chinese website!