The C Language

the type qualifiers const and volatile

A qualifier is a small word you attach to a type to add a promise or a warning. Two everyday ones are const and volatile. const says 'I promise not to change this through this name' — like a sign that reads READ ONLY. volatile says 'this value may change behind your back, so always re-check it' — like a clock face the compiler is forbidden to assume stays still.

const tells the compiler that, through this particular variable, the value will not be modified, so any attempt to assign to it is a compile error. This documents intent and lets the compiler catch accidental writes; it is heavily used on function parameters to promise a function will not alter what you pass it. volatile is rarer and lower-level: it forbids the compiler from optimizing away reads and writes, because the memory might be changed by hardware, by another thread of execution, or by a signal handler. Without volatile the optimizer might cache a value in a register and never notice it changed. Crucially, volatile is NOT a tool for thread synchronization — it does not provide atomicity or memory ordering; use real atomics or locks for that.

Why they matter: const is about safety and clear contracts — it is the everyday qualifier you will use constantly, especially with pointers, to express that data is read-only. volatile is a specialist's tool for memory-mapped hardware registers and certain signal-handling situations. Reaching for volatile to fix a concurrency bug is a classic mistake; it silences neither data races nor reordering across threads.

const int MAX = 100; /* MAX = 200; would not compile */ volatile int *status_reg = (int *)0x4000; int s = *status_reg; /* re-read every time; never cached */

const blocks writes through MAX at compile time; volatile forces an actual memory read of a hardware register on every access.

volatile is NOT for thread synchronization — it gives no atomicity and no memory ordering. Use C11 atomics or a mutex for shared state. const is a compile-time promise, not enforced memory protection; casting it away and writing is undefined behavior.

Also called
cv-qualifiers型別限定詞唯讀修飾詞