0 day streak
c / intermediate
Snippet

Const Correctness with Pointer Variations

Understanding where 'const' is placed is vital for API safety. A pointer to a constant ensures the data won't be modified, while a constant pointer ensures the pointer itself always points to the same memory location.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
void demonstrate_const() {
int val1 = 10, val2 = 20;
const int* p1 = &val1; // Pointer to constant int
// *p1 = 15; // Error: cannot modify data
p1 = &val2; // OK: can change address
int* const p2 = &val1; // Constant pointer to int
*p2 = 15; // OK: can modify data
// p2 = &val2; // Error: cannot change address
const int* const p3 = &val1; // Constant pointer to constant int
// p3 = &val2; // Error
// *p3 = 15; // Error
}
Breakdown
1
const int* p1
The data being pointed to is read-only through this pointer.
2
int* const p2
The memory address stored in the pointer is fixed and cannot be changed after initialization.