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

Performance: Prefix vs Postfix

Performance: Prefix vs Postfix

What you'll learn: Why using ++i is sometimes more efficient than i++ and how to choose the right one for your code.

The Hidden "Temporary" Variable

In C, the increment operator (++) can be placed before a variable (prefix) or after it (postfix). While they both add 1 to your variable, they handle the "result" of the expression differently.

Think of it like a coffee shop transaction.

  • Prefix (++i) is like paying for your coffee, getting your receipt, and then walking away. It’s a direct action: change the value, then report the new value.
  • Postfix (i++) is like being handed a copy of your old unpaid bill, paying it, and then the shop updates their records later.

To make i++ work, the computer has to remember what the value was before the increment happened so it can use that old value in the current expression. In technical terms, the compiler often has to create a "temporary copy" of the variable to hold that old value.

When Does It Matter?

In modern C programming, if you are just incrementing a variable on a line by itself, the compiler is usually smart enough to optimize both to be equally fast. However, it is a "best practice" to default to prefix (++i) unless you specifically need the old value.

#include <stdio.h>

int main() {
    int counter = 0;

    // This is efficient. It increments immediately.
    ++counter; 

    // This is slightly more complex. 
    // It saves '1', increments counter to '2', 
    // then returns the saved '1'.
    int result = counter++; 

    return 0;
}

Developing Good Habits

While the speed difference is microscopic for a single integer, the habit matters. As you move into more complex programming or embedded systems with limited power, those "temporary copies" can add up. By defaulting to ++i, you are telling the computer to do the simplest possible task: "Just add one and move on."

Use postfix (i++) only when your logic strictly requires the original value before the increase. Otherwise, stick to prefix to keep your code lean and mean.

Key takeaway

Use prefix (++i) by default to avoid the overhead of creating temporary copies of your data.