Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between const char* p, char * const p, and const char * const p in C
In C programming, *p represents the value stored at the address a pointer points to, and p represents the address itself. The const keyword can be applied to the char value, the pointer, or both. The thumb rule is to read declarations from right to left.
The Three Declarations
| Declaration | Read Right-to-Left | Change Value (*p)? | Change Pointer (p)? |
|---|---|---|---|
const char *p |
p is a pointer to a constant char | No | Yes |
char * const p |
p is a constant pointer to a char | Yes | No |
const char * const p |
p is a constant pointer to a constant char | No | No |
Note − const char * and char const * are identical. The position of const relative to * determines whether the value or the pointer is constant.
Example
The following program demonstrates all three types. Commented lines show operations that would cause compiler errors ?
#include <stdio.h>
int main() {
const char p = 'A';
const char r = 'C';
// --- const char* (pointer to constant char) ---
// Same as: char const* q
char const* q = &p;
// *q = 'B'; // ERROR: cannot change value through q
q = &r; // OK: pointer itself can be reassigned
printf("const char* q: %c
", *q);
// --- char* const (constant pointer to char) ---
char u = 'D';
char* const t = &u;
*t = 'E'; // OK: can change value through t
// t = &r; // ERROR: cannot reassign pointer t
printf("char* const t: %c
", *t);
// --- const char* const (constant pointer to constant char) ---
char const* const s = &p;
// *s = 'D'; // ERROR: cannot change value through s
// s = &r; // ERROR: cannot reassign pointer s
printf("const char* const s: %c
", *s);
return 0;
}
The output of the above code is ?
const char* q: C char* const t: E const char* const s: A
Conclusion
const char *p protects the value but allows the pointer to move. char * const p locks the pointer but allows the value to change. const char * const p locks both the value and the pointer. Read declarations right-to-left to quickly determine what const applies to.
