liveBook · Manning

Side effect

As explained in Modern C

A side effect is an observable change to program state caused by evaluating an expression or executing an operation.

A side effect changes an object or other program state while an expression is evaluated. In C, `an_object @= some_expression;` both computes a value and modifies `an_object`; increment and decrement operators behave similarly. section 4.2 section 19.0

Prefix, postfix, and chained modification

`++a` increments `a` before producing its result, whereas `a++` produces the old value before incrementing `a`. A chained expression such as `a = b = c += ++d` combines several modifications, making its evaluation difficult to follow. Write separate statements instead of relying on such expressions. section 4.2

TAKEAWAYS

  • Treat side effects inside value expressions as a readability and correctness hazard. section 4.2
  • Modify no more than one object in a statement. section 4.2
  • Do not assume that arithmetic operators or function calls evaluate operands or arguments in a particular order. section 4.5
  • Keep functions called inside expressions free of side effects when evaluation order matters. section 4.5

Unreliable argument order

In `printf("%g and %g\n", f(a), f(b));`, C does not establish whether `f(a)` or `f(b)` runs first. If either function modifies state relevant to the other, the result can depend on compiler choices or surrounding code. section 4.5

Side effects are one kind of effect. Program execution can also change its point of execution, intermediate values, or hidden state such as lock and atomic-flag state. Even `(void)0` has an effect because execution advances to the next evaluation. section 19.0

How Modern C covers it

How deep it goes
Explains object modification, prefix/postfix results, operand sequencing, and broader execution effects, while deferring detailed concurrency treatment.
Examples
Uses compound assignment, chained modification, postfix and prefix increment, function arguments, and a discarded expression.
What it assumes
Assumes basic C expressions, objects, operators, function calls, and execution flow.
What you can do after
Diagnose expressions whose results depend on hidden modifications or unspecified evaluation order, then rewrite them as separate operations.
How it connects
Connects side effects with assignment operators, increment and decrement operators, evaluation order, function calls, sequence points, atomic objects, and threads.

Also explained in

Compare how 24 books explain side effect →

Related concepts

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