What are Sequence Points in C++?
In C++, sequence points define the order in which expressions involving side effects are evaluated such that all side effects of previous evaluations are guaranteed to be complete, and no side effects from subsequent evaluations have started, here a side effect is a change in the system state that can be a change in the value of an object, or any modification of an object.
Sequence Points in C++ Operations
The following operations in C++ introduce sequence points:
- The end of a full expression (a statement).
- The end of a function call.
- After the evaluation of the first operand of the comma operator(,)
- After the evaluation of the first operand of the logical AND (
&&
), logical OR (||
), and conditional (?:
) operators.
Rules of Sequence Points
- Full expressions are sequenced in order of execution.
- Operand evaluation is generally sequenced before operation execution, but the order among operands may be unspecified.
- Increment operators (
++
) sequence value computation before modifying the operand. - The comma operator introduces a sequence point, sequencing operations on its left before evaluating its right.
- In the conditional operator, the condition is evaluated and sequenced before either operand.
- After a return statement in a function, all side effects of the expression being returned are completed before proceeding.
How Do Sequence Points Relate to Undefined Behaviour in C++?
In C++, sequence points are used to determine the order of evaluation of expressions to avoid undefined behavior in our programs. In this article, we will learn how do sequence points relate to undefined behavior in C++.