Course contentsShow
← C
Lesson 223 of 1,2193. Operators and ExpressionsFree lesson

Sequence points in logic `&&` and `||`

Sequence points in logic && and ||

What you'll learn: How logical operators act as "traffic lights" that force the computer to finish all pending updates before moving to the next part of your code.

In C, we often talk about "side effects"—the moment a variable’s value actually changes, such as when you use x++. Normally, the compiler has some freedom to decide exactly when that change happens during a line of code. However, the logical AND (&&) and logical OR (||) operators introduce a strict rule called a sequence point.

The "Stop and Sync" Rule

Think of a sequence point like a checkpoint in a race. Even if the runners (your code operations) are sprinting ahead, they must all reach the checkpoint and sync up their progress before anyone is allowed to cross into the next section.

When C evaluates A && B, it follows a two-step process:

  1. It evaluates everything on the left side (A).
  2. It guarantees that all side effects (like increments or assignments) from the left side are fully completed and saved to memory before it even looks at the right side (B).

This is crucial because it allows you to change a variable on the left and safely use its new value on the right.

Seeing it in Action

Look at how the sequence point prevents chaos in this example:

#include <stdio.h>

int main() {
    int count = 5;

    // The sequence point at && ensures count becomes 6 
    // BEFORE the right side is evaluated.
    if (count++ > 5 && count == 6) {
        printf("This will run because count is now 6!\n");
    }

    int index = 0;
    int arr[5] = {10, 20, 30, 40, 50};

    // The sequence point ensures index++ finishes before 
    // we use it to access the array.
    if (index++ < 5 && arr[index] == 20) {
        printf("Array accessed at index 1.");
    }

    return 0;
}

Why it matters

Without this sequence point, the compiler might try to evaluate arr[index] at the same time it is trying to increment index. This would result in "undefined behavior," where your program might crash or give different results on different computers.

Because && and || are sequence points, they provide a safety barrier. If the left side changes a value, you can bet your bottom dollar that the right side will see that updated value.

Key takeaway

Logical && and || act as barriers that force all variable updates on the left to finish before the right side starts.