C/C++ Arena

Step 5 of 6

Prefix vs postfix ++

Used on a line by itself, x++; and ++x; do the same thing: add 1 to x. They only differ when the result is used inside a bigger expression, because the expression gets a value from them:

#include <stdio.h>

int main(void) {
    int n = 10;
    int first = n++;
    printf("first=%d n=%d\n", first, n);
    int second = ++n;
    printf("second=%d n=%d\n", second, n);
    return 0;
}
first=10 n=11
second=12 n=12

Walk through it: first = n++ copies the old value (10) into first, then n becomes 11. second = ++n bumps n to 12 first, then copies 12 into second.

Keep it simple

This rule matters for reading other people's code, but in your own code prefer to keep ++ on its own line. Expressions that change a variable and also use it again, like n = n++ + 1 or printf("%d %d", n, n++), are undefined behavior in C: the language doesn't say what happens, and different compilers give different results. The safe rule: if a statement changes a variable, don't use that same variable anywhere else in the statement. (printf("%d %d", n, n++) changes n only once, but it also reads n elsewhere, and that's already undefined.)

Your turn: make the program print 5 7 7 by choosing prefix or postfix for each blank. The variable a starts at 5.

Previous: Shorthand operators Next: Put it together