liveBook · Manning

Unsequenced operation

As explained in Modern C, Third Edition

Unsequenced evaluation is an evaluation relationship in which the relative order of two evaluations is not specified and they may be interleaved.

An unsequenced operation is an evaluation relationship in which the relative order of two evaluations is not specified. Function-argument expressions, for example, may execute in either order or be interleaved, allowing optimizing compilers more freedom. section 19.2

Modifying and reading the same object

printf("%lld\n", x++ + x); is unsafe because the update of x may occur before, after, or while the other read occurs. The result can be twice the initial value, the initial value plus one, or a value assembled from different computation phases. TAKEAWAY: Don’t read and modify the same object within one arithmetic expression. section 15.3.2

Pointer aliases

printf("%lld\n", (*p)++ + (*q)); is safe only if p and q designate different objects. If p == q, the expression has the same underlying collision as the direct-variable example, even when the pointers were assigned in unrelated parts of the program. section 15.3.2

Sequence points impose serialization between parts of execution, but they do not generally dictate which independent expressions run first. Signal handlers and concurrent threads create related unsequenced accesses that require special conditions and mechanisms. section 19.2 section 15.3.2

How Modern C, Third Edition covers it

How deep it goes
Defines unsequenced evaluation, demonstrates direct and pointer-based hazards, and connects them to sequence points, signals, and threads.
Examples
Uses x++ + x, (*p)++ + (*q), and paired pointer updates that produce different outputs.
What it assumes
Assumes familiarity with C expressions and introduces sequence points as the framework for reasoning about evaluation order.
What you can do after
Apply the safety rule by separating reads and modifications of one object across an arithmetic expression.
How it connects
Connects sequencing with sequence points, pointer aliasing, signal handlers, threads, and optimizing compilers.

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.