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 int*, const int * const, and int const * 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 either the pointer, the value it points to, or both, creating different levels of immutability.
The thumb rule for reading these declarations is to read from right to left.
The Three Declarations
| Declaration | Read Right-to-Left | Change Value (*p)? | Change Pointer (p)? |
|---|---|---|---|
const int *p |
p is a pointer to a constant int | No | Yes |
int const *p |
p is a pointer to a constant int (same as above) | No | Yes |
const int * const p |
p is a constant pointer to a constant int | No | No |
Note − const int * and int 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 int p = 5;
const int r = 7;
// --- const int* (pointer to constant int) ---
// Same as: int const* q
const int* q = &p;
// *q = 7; // ERROR: cannot change value through q
q = &r; // OK: pointer itself can be reassigned
printf("const int* q: %d
", *q);
// --- const int* const (constant pointer to constant int) ---
const int* const s = &p;
// *s = 7; // ERROR: cannot change value through s
// s = &r; // ERROR: cannot reassign pointer s
printf("const int* const s: %d
", *s);
// --- int* (regular pointer for comparison) ---
int x = 10;
int* t = &x;
*t = 20; // OK: can change value
t = (int*)&r; // OK: can reassign pointer
printf("int* t: %d
", *t);
return 0;
}
The output of the above code is ?
const int* q: 7 const int* const s: 5 int* t: 7
Conclusion
const int * (or int const *) makes the pointed-to value immutable but allows reassigning the pointer. const int * const makes both the value and the pointer immutable. Read declarations from right to left to understand what const applies to.
