Course contentsShow
← C
Lesson 937 of 1,21913. Advanced CFree lesson

Sequence point violations

Sequence point violations

What you'll learn: Why trying to modify the same variable twice in a single statement leads to unpredictable "time travel" bugs in your code.

The "When" Problem

In C, we often think the computer executes every tiny detail of a line from left to right. However, the C standard gives the compiler a lot of freedom to rearrange small operations to make your program faster. To keep things sane, the language uses sequence points.

A sequence point is like a "save game" marker. It is a point in the code—usually at the semicolon (;)—where all previous calculations and changes to variables must be finished before the next statement begins. Between these markers, however, the compiler can perform operations in almost any order it wants.

The Violation

A sequence point violation occurs when you try to change the value of a variable twice, or change it and use it, within the same step. Because the compiler hasn't hit a "save marker" yet, it might perform those changes in an order you didn't expect.

Imagine a chef (the compiler) being told: "Add salt to the pot, but also double the amount of salt that was already in there." If the chef adds the pinch first and then doubles it, you get a different result than if they doubled the original amount and then added the pinch. C does not guarantee which happens first.

Code That Breaks the Rules

The most common trap involves the increment (++) operator. Look at this example:

#include <stdio.h>

int main() {
    int i = 5;

    // VIOLATION: Modifying 'i' twice before a sequence point
    i = i++; 

    // VIOLATION: Using 'i' and modifying it in the same step
    int result = i + ++i; 

    printf("%d\n", i);
    return 0;
}

In i = i++, you are asking the computer to assign a value to i and increment i at the same time. On one compiler, i might stay 5; on another, it might become 6. This is Undefined Behavior. Your program might crash, give a wrong answer, or even work perfectly until you try to run it on a different computer.

How to Stay Safe

The rule of thumb is simple: One modification per variable, per semicolon. If you need to increment a value and then use it in a calculation, do it on two separate lines. This forces a sequence point (the semicolon) between the actions, ensuring the compiler finishes the first task before starting the second.

Key takeaway

Never modify the same variable more than once in a single expression, or the compiler may rearrange your logic in unpredictable ways.