Pointers
Pointer To Const
A pointer to const allows reading through the pointer while protecting the pointed-to value from writes through that pointer.
const pointee
`const int *ptr` means the `int` cannot be changed through `ptr`.
reassign pointer
The pointer itself can still be changed to read a different object.
Pointer To Const
pointer_to_const.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int first = 4;
int second = 6;
int useSecond = 0;
const int *ptr = &first;
if (useSecond) {
ptr = &second;
}
printf("read=%d\n", *ptr);
return 0;
}
#include <stdio.h>
int main(void) {
int first = 7;
int second = 6;
int useSecond = 0;
const int *ptr = &first;
if (useSecond) {
ptr = &second;
}
printf("read=%d\n", *ptr);
return 0;
}
#include <stdio.h>
int main(void) {
int first = 10;
int second = 6;
int useSecond = 0;
const int *ptr = &first;
if (useSecond) {
ptr = &second;
}
printf("read=%d\n", *ptr);
return 0;
}
#include <stdio.h>
int main(void) {
int first = 4;
int second = 6;
int useSecond = 1;
const int *ptr = &first;
if (useSecond) {
ptr = &second;
}
printf("read=%d\n", *ptr);
return 0;
}
first ← 4, second ← 6, useSecond ← 0, ptr ← ⟨addr A⟩
3int main(void) {4 int first→ 4 = 4; //@first=7, 105 int second→ 6 = 6;6 int useSecond→ 0 = 0; //@useSecond=17 const int *ptr→ ⟨addr A⟩ = &first4;89 if (useSecond) {10 ptr = &second;11 }1213 printf("read=%d\n", *ptr⟨addr A⟩);14 return 0;15}outputread=4
first ← 7, second ← 6, useSecond ← 0, ptr ← ⟨addr A⟩
3int main(void) {4 int first→ 7 = 7;5 int second→ 6 = 6;6 int useSecond→ 0 = 0;7 const int *ptr→ ⟨addr A⟩ = &first7;89 if (useSecond) {10 ptr = &second;11 }1213 printf("read=%d\n", *ptr⟨addr A⟩);14 return 0;15}outputread=7
first ← 10, second ← 6, useSecond ← 0, ptr ← ⟨addr A⟩
3int main(void) {4 int first→ 10 = 10;5 int second→ 6 = 6;6 int useSecond→ 0 = 0;7 const int *ptr→ ⟨addr A⟩ = &first10;89 if (useSecond) {10 ptr = &second;11 }1213 printf("read=%d\n", *ptr⟨addr A⟩);14 return 0;15}outputread=10
first ← 4, second ← 6, useSecond ← 1, ptr ← ⟨addr A⟩
3int main(void) {4 int first→ 4 = 4;5 int second→ 6 = 6;6 int useSecond→ 1 = 1;7 const int *ptr→ ⟨addr A⟩ = &first4;ptr ← ⟨addr B⟩
9if (useSecond1) {10 ptr→ ⟨addr B⟩ = &second6;11}printf("read=%d ", *ptr);
13 printf("read=%d\n", *ptr⟨addr B⟩);14 return 0;15}outputread=6