Postfix decrement x--
What you'll learn: How to use the postfix decrement operator to decrease a variable's value immediately after its current value is used in an expression.
The "Use it, then change it" rule
In C, the postfix decrement operator (-- placed after a variable) is a shortcut for subtracting one. However, it comes with a specific behavior regarding timing. Think of it like a "buy now, pay later" coupon. When you use x-- in a line of code, C uses the original value of x for whatever calculation is happening right now, and only after that calculation is finished does it subtract one from the variable.
Imagine you are holding a stack of five plates. If someone asks, "How many plates do you have?" you answer "Five." As soon as you finish answering, you set one plate aside on the counter. You now have four plates, but the person who asked only heard the number five. That is exactly how x-- works.
Seeing it in action
The distinction between the value returned by the expression and the final value of the variable is the most important part to master.
#include <stdio.h>
int main() {
int cookies = 10;
// We use postfix decrement here
// It prints the current value (10), THEN subtracts 1
printf("I have %d cookies.\n", cookies--);
// Now that the previous line is finished, we see the update
printf("Wait, now I only have %d cookies.\n", cookies);
return 0;
}
In the code above, the first printf doesn't see the number 9. It grabs the 10, hands it to the function to be printed, and while the computer is moving on to the next line of code, it quietly updates cookies to 9.
Why use it?
You will most commonly see postfix decrement in loops or when managing countdowns. It allows you to process an item at a specific index and move the pointer or counter backward in a single, elegant motion. It keeps your code concise by combining two steps—using a value and updating it—into one operation. Just remember the order: the "post" in postfix means the subtraction happens after the variable is accessed.
Key takeaway
The x-- operator evaluates to the current value of x first, then decreases the actual variable by one.