</>EmbeddedInterview

What is a sequence point?

HardC Programming

Short answer: A sequence point is a point in the execution where all side effects of earlier evaluations are complete and none of the later ones have started. If an object is modified twice, or modified and also read for another purpose, without a sequence point (in C11 terms, without being "sequenced before") between them, the behaviour is undefined.

Where sequence points are (C99 terms)

  • At the end of a full expression (the ;, the condition of if/while/for, a return expression).
  • After the first operand of &&, ||, ?: and the comma operator.
  • After evaluating a function's arguments, just before the call.

Undefined examples

i = i++ + 1;        /* i modified twice */
a[i] = i++;         /* i read (for the index) and modified, unsequenced */
f(i++, i++);        /* the two arguments are unsequenced relative to each other */
x = y++ * y++;      /* y modified twice */

Well-defined examples

i++, j = i;               /* comma operator: i++ completes first */
if (p != NULL && p->ok)   /* && sequences and short-circuits */
x = (i++ > 0) ? i : 0;    /* ?: sequences after the condition */

C11 terminology: "sequenced before", "unsequenced" and "indeterminately sequenced" replaced "sequence point". The practical rule is unchanged: do not modify a variable more than once in one expression, and do not read it elsewhere in an expression that modifies it.

Note on function arguments: the order in which f(a(), b()) calls a and b is unspecified (either order is allowed, but it is not UB as long as they do not touch the same object without sequencing). Code that depends on that order is still a bug.

Embedded twist: reading a volatile hardware register twice in one expression (STATUS + STATUS) gives unspecified order of the two reads; with registers that clear on read, that matters. Read into a local first.