liveBook · Manning

Const qualifier

As explained in Modern C, Third Edition

A const-qualified type is a C type whose referenced value is not modifiable through an expression having that type.

A const-qualified type makes the referenced value read-only through an expression having that type. Attempting to modify such an object should produce a compiler diagnostic. section 5.6.1

Qualification applies at each level

The declaration `char const*const` combines two guarantees: the characters referred to are not writable through the pointer, and the pointer itself cannot be redirected. An array such as `bird` can therefore refer to string literals without storing those characters inside the array. section 5.6.1

Read-only through one type does not guarantee an unchanging value. Another part of the program may access the same object without the qualification and change it. Thus const-qualified objects differ from C23 `constexpr` objects, whose values are known at compile time and guaranteed not to change. section 5.6.1

Keep these rules distinct:

  • Treat string literals as read-only, even though their historical C type was retained for backward compatibility rather than declared as `char const[]`. section 5.6.1
  • Handle const-qualification carefully in text-processing interfaces, where pointer types and buffer overflow are related safety concerns. section 14.7
extern double const factor;
constexpr double π = 3.141'592'653'589'793'238'46;

Compare a declaration-only const-qualified object with a C23 constexpr object whose compile-time value is fixed. section 5.6.1

How Modern C, Third Edition covers it

How deep it goes
Explains object and pointer qualification, alias-based mutation, string-literal history, and the boundary with constexpr.
Examples
Uses char const*const, string-literal arrays, extern double const, and constexpr declarations as concrete examples.
What it assumes
Assumes basic C declarations, arrays, pointers, and objects while distinguishing const qualification from constexpr.
What you can do after
Evaluate/understand which values and pointer targets an expression may modify.
How it connects
Connects const qualification to string literals, pointers, arrays, constexpr, and buffer overflow.

Also explained in

Compare how 7 books explain const qualifier →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.