c / intermediate
Snippet
Constant Pointers vs. Pointers to Constants
The placement of the 'const' keyword determines what is immutable. 'const int *' means the data being pointed to cannot be changed via that pointer. 'int * const' means the pointer address itself cannot be changed after initialization.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>int main() {int val = 10, other = 20;const int *ptr1 = &val; // Pointer to constantint * const ptr2 = &val; // Constant pointerptr1 = &other; // OK: pointer can change// *ptr1 = 15; // Error: value is constant*ptr2 = 15; // OK: value can change// ptr2 = &other; // Error: pointer is constantreturn 0;}
Breakdown
1
const int *ptr1 = &val;
The integer value is constant from the perspective of ptr1.
2
int * const ptr2 = &val;
The pointer address stored in ptr2 is fixed and cannot point elsewhere.