YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Language detailsChapter 16 of 73

Qualifiers: read-only access and observable effects

Understand const access paths, then revisit optional pointer, volatile, restrict, and atomic contracts.

8 min readFoundationsC17 + C23 notes
Offline reading
In this chapter9 sections

Sometimes code should read a value without changing it through that access. Sometimes access itself has special rules. Type qualifiers describe these restrictions and effects; understanding which part of a declaration they qualify is the key.

Read the first two sections now. The optional pointer and concurrency sections are return points after the Memory & data and Correctness & care units; nothing here is a prerequisite lock.

1. const makes an access read-only

An object defined as const int limit = 4; cannot be assigned a new value. An attempted write through a const-qualified lvalue violates a language constraint and requires a diagnostic. Casting away the qualification does not make a truly const-defined object writable: modifying it has undefined behavior.

But a read-only view of a mutable object does not freeze that object. In the next example, view is a pointer: a value that designates the existing score object. The star in *view accesses the designated object. The view forbids a write through that path, while a direct write to the mutable score remains valid.

C17 · illustrative fragment
int score = 10;
const int *view = &score;
score = 12;
int observed = *view;

observed becomes 12. There is one score object, not a frozen copy. Use a read-only parameter when a function should inspect supplied data without modifying it through that parameter. It is not a promise that no other actor can change the data.

An intentional diagnostic: assigning to a const object

This is invalid C17. It is shown to explain the constraint, not as a program with a predictable runtime result.

C17 · intentional build rejection
int main(void)
{
    const int limit = 4;
    limit = 5;
    return 0;
}

2. Read-only and constant expression are different ideas

const is a type property. An Integer constant expression is an expression admitted by particular translation-time rules. In C17, reading an ordinary const integer object does not become an integer constant expression simply because its initializer is 4. An optimizer knowing the value cannot change that language classification.

Use a C17 enumeration constant for a small named integer needed in an array bound or case label. Use a typed const object for read-only data. C23 adds constexpr for named constant objects under specific initialization constraints; it does not turn C into C++ or allow arbitrary function calls in constant expressions. The dedicated constant expressions chapter explains the choices.

3. Optional: qualify the pointer or the pointed-to type

Read after the pointer introduction

const int *reader permits changing reader to designate another object, but disallows writing an int through it. int *const fixed fixes the pointer value; the designated mutable int can still change. const int *const fixed_reader combines both restrictions.

Complete C17 program
#include <assert.h>

int main(void)
{
    int first = 10;
    int second = 20;
    const int *reader = &first;
    int *const fixed = &first;
    const int *const fixed_reader = &first;

    reader = &second;
    *fixed = 15;
    assert(*reader == 20);
    assert(*fixed_reader == 15);
    return 0;
}

A typedef can hide a pointer level. In this declaration, const IntPointer means a const pointer to int, not a pointer to const int. A type alias names the complete type it denotes.

C17 · illustrative fragment
typedef int *IntPointer;
int value = 7;
const IntPointer fixed = &value;
*fixed = 8;

The write to value is valid; reassigning fixed would not be. Const qualification is also not a recursive freeze of objects reachable through pointer members. Do not force int ** into const int **: adding qualification across multiple pointer levels has stricter compatibility rules. Revisit types and data interfaces before using nested pointer APIs.

4. volatile describes observable accesses

volatile gives accesses special observable semantics. The implementation defines exactly what counts as an access. Device-register access must follow the target's documented hardware and compiler rules; ordinary ISO C alone does not describe a particular address or device protocol.

C17 · illustrative fragment
volatile int status = 0;
int before = status;
status = 1;
int after = status;

Here before is 0 and after is 1. This small local example illustrates source-level accesses; it does not simulate an interrupt or test a device. Volatile is not a request to make every operation slow, a general cache-flush command, an atomic increment, or synchronization between threads.

A volatile sig_atomic_t flag is useful in the restricted asynchronous signal-handler assignment idiom. That does not permit arbitrary library calls, general shared data access, or using volatile as a thread-safety mechanism. Signals need their own platform and language contracts.

5. Optional: restrict and atomic access solve other problems

Read after arrays, pointers, and shared state

restrict is a scoped access contract. If a relevant object is modified during the associated execution, the ways it is accessed must obey the restricted-pointer rules. Merely having another pointer value is not automatically a violation; read-only aliasing has different treatment. Promise it only when callers can satisfy the actual access contract.

Complete C17 program
#include <assert.h>
#include <stddef.h>

static void double_into(size_t count,
                        int *restrict destination,
                        const int *restrict source)
{
    for (size_t i = 0; i < count; ++i) {
        destination[i] = 2 * source[i];
    }
}

int main(void)
{
    const int input[3] = { 2, 3, 4 };
    int output[3] = { 0 };
    double_into(3, output, input);
    assert(output[0] == 4 && output[1] == 6 && output[2] == 8);
    return 0;
}

The displayed call uses distinct input/output arrays. In general the function requires accessible regions of at least count ints, no conflicting overlap for its modified/read elements, and source values whose doubling is representable as int. A cast cannot repair a broken promise. See effective types and aliasing for the deeper rules.

_Atomic int gives an atomic integer type on an implementation with atomic support. The atomic operation below updates one object indivisibly; relaxed order does not publish unrelated ordinary data. This single-thread example checks the value change, not a concurrent algorithm.

Complete C17 program
#include <assert.h>
#include <stdatomic.h>

#ifdef __STDC_NO_ATOMICS__
#error This example requires atomic support
#endif

int main(void)
{
    _Atomic int visits = 0;
    int previous = atomic_fetch_add_explicit(&visits, 1,
                                              memory_order_relaxed);
    int current = atomic_load_explicit(&visits, memory_order_relaxed);
    assert(previous == 0 && current == 1);
    return 0;
}

Atomic support is conditional in C17/C23. A whole operation involving multiple objects, a resource lifetime, or an invariant needs a complete synchronization design. See threads and shared state; neither volatile nor a single atomic field certifies that design.

6. Thought check: can a read-only view observe change?

Consider a mutable score viewed through const int *. Can its next read differ?

Yes. Another valid access can modify the mutable object while the view remains read-only. In a threaded program, the reads and writes must additionally be synchronized as required; const does not remove data races. Qualification, lifetime, and synchronization answer different questions.

Sources and further reading

Primary references: WG14 N1570 6.2.4, 6.3.2.3, 6.7.3, 6.7.8, 7.14.1.1, and 7.17; WG14 N3096 (C23 notes). These are public committee drafts; the examples here use a C17 baseline.

Before you move on

  • Qualifiers apply to particular types and access paths in a declaration.
  • const access restricts modification through that path without freezing every alias to a mutable target.
  • volatile, restrict, and atomic facilities have specific contracts that do not replace one another.
Keep these ideas separate
const pointer / Pointer to const
One fixes the pointer object; the other restricts modification of the target through that access.
Explain it in your own words

What would you inspect to identify which part of a pointer declaration const qualifies?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

Does accessing a modifiable object through const int * make the original object globally immutable?
Read the explanation for every choice
  1. No. This access path is read-only, but another permitted access can modify the original object.

    ✓ Correct reasoning. This does not permit modifying an object that was originally defined as const.

  2. Yes, every alias becomes read-only automatically.

    Qualifying one access path does not rewrite all other pointer objects and types.

  3. The pointed-to object is copied into the pointer.

    A pointer value refers to an object; it does not contain a copy of that object.

C17

Quick reference from the earlier edition

Retained for existing section links and saved passages. Exact corrections are recorded in the source review.

Building on the brief definitions in Section 7, this section looks at how qualifiers and storage classes actually shape a program's behavior.

const in Depth

const alone doesn't tell you what's constant — its position relative to * does:

C17 · illustrative fragment
int value = 10;
const int *read_only = &value;       /* cannot change value through read_only */
int *const fixed = &value;           /* fixed cannot be reassigned; *fixed can change */
const int *const both_fixed = &value; /* neither reassignment nor writes through it */

volatile in Depth

volatile requires the implementation to preserve the specified observable accesses; the exact meaning of an access is implementation-defined. Typical uses include memory-mapped device registers under the platform's rules and a volatile sig_atomic_t flag for the restricted signal-handler idiom. It does not make a read-modify-write indivisible or establish a happens-before relationship between threads. A shared volatile counter can still have a data race; use _Atomic or a mutex where required.

restrict (C99)

restrict is an aliasing/access contract, not a claim that no other pointer value exists. In the associated block execution, if an object accessed through a restricted pointer is also modified, accesses to that object must follow the restricted-pointer rules, normally using that pointer or values derived from it. Aliasing of objects that are only read is permitted. Violating the contract is undefined behavior; it is mainly useful for optimization in carefully designed array-processing interfaces.

Storage Duration, Scope, and Linkage

Keep three different concepts separate: an object has a storage-duration category that determines its lifetime rules, while an identifier has a scope and may have linkage. A function or typedef name is not an object with automatic/allocated storage duration. The main categories are:

  • Storage duration — automatic (ordinary non-VLA local objects whose lifetime follows block execution; a VLA instead lives from its declaration until execution leaves that declaration’s scope), static (exists for the entire program, as with globals or static locals), allocated (storage obtained through allocation functions, lasting until deallocated by free or replaced by a successful realloc), and thread (C11's _Thread_local, giving each thread its own independent copy).
  • Scope — block scope (visible only within its enclosing { }), file scope (visible from its point of declaration to the end of the translation unit), function prototype scope (parameter names inside a prototype), and function scope (labels used as goto targets).
  • Linkage — external (declarations of the same identifier across translation units refer to the same object or function), internal (declarations of the same identifier within one translation unit refer to the same object or function, commonly established by file-scope static), and none (each declaration introduces a distinct entity, as with ordinary locals and parameters). Linkage connects declarations; it does not itself make a name visible.

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 16 / 73

In this chapter

Qualifiers: read-only access and observable effects

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping