Skip to main content

Sequence Points in C

In C programming language, a sequence point is a point in the execution of a program where the evaluation of all expressions before the sequence point is guaranteed to be complete and their effects will have taken place. In other words, it is a point where the state of the program is guaranteed to be well-defined.

Sequence points are important in C because they help to define the order in which expressions are evaluated, and ensure that the behavior of a program is well-defined. The C standard defines several sequence points, including:

  1. At the end of a full expression: This includes expressions that end with a semicolon, as well as function calls, assignments, and other statements that are treated as full expressions.

  2. At the "&&" and "||" operators: These operators are sequence points, which means that the left-hand side of the operator is fully evaluated before the right-hand side is evaluated.

  3. At the ternary operator "? :": The evaluation of the condition expression is a sequence point, as is the evaluation of either the true or false expression.

  4. At the comma operator: The comma operator is a sequence point, which means that the left-hand side of the comma is evaluated before the right-hand side.

Understanding sequence points is important in C programming, as it can affect the behavior of expressions and the order in which they are evaluated. It is also important to note that some expressions may not have a well-defined behavior if they rely on undefined order of evaluation, which can lead to unexpected results.

Example

#include <assert.h>
#include <stdio.h>

int main()
{
	int a = 10;
	int b = 20;
	int c = (++a, b++);
	printf("a is %d\n", a);
	printf("b is %d\n", b);
	printf("c is %d\n", c);
	return 0;
}

Output

a is 11
b is 21
c is 20

In this example, the third line of code assigns the value of c to 20. This is because of the sequence point provided by the comma operator. The comma operator first evaluates the expression ++a, which increments the value of a to 11. This is a sequence point, so the increment of a is guaranteed to happen before the next expression is evaluated. Then the comma operator evaluates the expression b++, which increments the value of b to 21. However, the value of b++ is the original value of b before the increment, which is 2. Therefore, the value of c is 2.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment