A side-effect is a programming term that refers to intended changes in the program behavior, such as a variable changing value. It is in important term when discussing compiler optimization and expression evaluation.
A side-effect is a programming term that refers to intended changes in the program behavior, such as a variable changing value. It is in important term when discussing compiler optimization and expression evaluation.
Most notably, this term is often used in the C and C++ languages. One formal definition of the term can be found in ISO 9899:2011 (C11) 5.1.2.3 §2:
Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression in general includes both value computations and initiation of side effects.
C++ contains an identical definition, see for example C++11 1.9/12.
When a compiler optimizes code, it has to ensure that it removes no side effects (C11 5.1.2.3 §4):
In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).
Therefore the volatile
qualifier is often used to prevent the compiler from optimizing cerain parts of the code, since any access (read/write) to a volatile object is considered a side effect.
Side effects is also an important term when discussing expression evaluation. For example, expressions that contain multiple side effects on the same variable, with no so-called "sequence point" in between, invokes undefined behavior, see Undefined behavior and sequence points.