C const Pointers
Tell apart a pointer to const data and a const pointer to mutable data.
How it works
const can qualify the pointed-to type, the pointer object, or both. const int *view permits moving view to another valid int but prevents writing through *view. int *const owner prevents changing the stored pointer while permitting modification of its int. Neither spelling expresses ownership or allocation length. Read a declaration around the identifier and make the intended access rule part of the helper signature so the compiler can reject accidental writes through a read-only view.
Run it locally
Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.
cc -std=c17 -Wall -Wextra -Wpedantic -Werror const-pointers.c -o lessonOn Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.
Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.
Example
#include <stdio.h>
int main(void) {
int depth = 20;
int replacement = 25;
const int *view = &depth;
int *const selected = &depth;
*selected = 23;
printf("Viewed: %d\n", *view);
view = &replacement;
printf("Other: %d\n", *view);
return 0;
}
Expected result
Viewed: 23
Other: 25
The read-only view observes a change made through a different permitted alias. const is an access rule through a type, not a promise that an object never changes by any means. The const pointer stays connected to depth throughout its lifetime. Casting away const does not make an originally const object writable and can conceal a design error.
For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.