liveBook · Manning

Side effect

As explained in Modern C, Third Edition

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

A side effect is a change to program state caused while evaluating an expression or executing an operation. In C, modifying an object, storing a value, performing I/O, or changing relevant hidden state can affect later evaluation. section 4.3 section 21.0

Keep side effects separate from value computation:

  • Assignment operators, ++, and -- return a value while also modifying an object. section 4.3
  • Prefix increment modifies first and returns the new value; postfix increment returns the old value and modifies afterward. section 4.3
  • Most operators and function calls do not sequence their operands or argument expressions, so side effects can make the result depend on evaluation order. section 4.6
  • Avoid modifying more than one object in a statement and avoid side-effecting function calls inside expressions. section 4.3 section 4.6

Sequencing changes what an expression observes

In `printf("%g and %g\n", f(a), f(b));`, the two function arguments have no guaranteed evaluation order. If either call changes state relevant to the other, the result depends on which call runs first. Separate the calls into statements when their effects matter. section 4.6

an_object @= some_expression;

The compound-assignment form `an_object @= some_expression;` makes an object modification explicit and keeps the side effect at statement level. section 4.3

How Modern C, Third Edition covers it

How deep it goes
Explains modification, prefix and postfix results, sequencing, and hidden state, but stops short of detailed concurrency mechanics.
Examples
Uses compound assignment, prefix and postfix increment, chained assignments, and function calls with side-effecting arguments.
What it assumes
Assumes familiarity with C expressions, objects, operators, assignments, and function calls.
What you can do after
Evaluate and write C expressions without relying on unsequenced side effects or accidental operand order.
How it connects
Connects side effects to assignment operators, increment and decrement, evaluation order, sequencing, function calls, and atomic access.

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, Third Edition. The section links point to the parts of the book it draws on.