const and volatile in C
const is a compiler-enforced promise not to modify: const int LIMIT = 100; cannot be reassigned, and const char *p (pointer to const) forbids writes through p. It documents intent, enables optimizations, and turns accidental mutation into compile errors.
volatile is the opposite promise — about the compiler, not you: the value may change from outside the program's visible flow (hardware registers, interrupt flags, other threads), so every read must actually happen and no access may be optimized away. Embedded and systems code lives on volatile; application code rarely needs it.
const locks the binding
const int LIMIT = 100; can be read but never assigned — violations fail at compile time, not in testing.
Read const-pointer declarations inside out
const char *p reads right-to-left: pointer to const char (can't modify through p); char * const p is a const pointer to mutable char.
volatile forbids optimization
volatile int flag; forces every read/write to really occur — the compiler may not cache it in a register or skip repeats.
Where each belongs
const everywhere a value is fixed (limits, table data, read-only parameters); volatile on hardware registers and cross-context flags.
#include <stdio.h> int main(void) { const int limit = 10; const char *msg = "hi"; printf("%d %s\n", limit, msg); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.