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

Prefix decrement `--x`

Prefix decrement --x

What you'll learn: How to use the prefix decrement operator to decrease a variable's value immediately before it is used in an expression.

The "Pay First" Rule

In C, the double minus sign (--) is the decrement operator. Its job is simple: subtract exactly 1 from a variable. However, where you place those minus signs matters immensely. When you place them before the variable name (like --x), it is called a prefix decrement.

Think of the prefix decrement like a "pay-at-the-door" policy for a concert. You cannot enter the venue or enjoy the show until you have handed over your ticket. In programming terms, the variable must "pay" its value (decrease by 1) before the rest of the code is allowed to look at it or use it.

How it works in code

When the computer sees --x, it performs two steps in a specific order:

  1. It immediately subtracts 1 from the value stored in x.
  2. It then uses that brand-new, smaller value for whatever calculation is happening.

Let's look at how this behaves in a real scenario:

#include <stdio.h>

int main() {
    int cookiesInJar = 10;

    // We use prefix decrement here
    // The value changes to 9 FIRST, then it is printed
    printf("I took one! Now there are %d cookies.\n", --cookiesInJar);

    // If we check the variable again, it stays 9
    printf("Current count: %d\n", cookiesInJar);

    return 0;
}

Why the "Pre" matters

If you are just subtracting 1 on a line by itself, --x; works exactly like x = x - 1;. However, the prefix version is unique when you combine it with other actions.

Imagine you are at the top of a slide. If the "slide" is a printf statement, the prefix decrement means you slide down one level before anyone takes a photo of you. You don't get "captured" at your original height; you are captured only after you have already descended.

This is particularly useful in loops or complex math where you need to ensure a counter is lowered before the very first time you check it. It ensures your data is "freshly updated" the moment it hits the expression.

Key takeaway

Prefix decrement (--x) subtracts one from a variable immediately and returns the updated value to the rest of the expression.