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:
x++(postfix) gives the old value ofx, then increments it.++x(prefix) incrementsxfirst, then gives the new value.
#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 task
Make the program print 5 7 7 by choosing prefix or postfix for each blank. The variable a starts at 5.
Challenge 2
Now with --. The variable x starts at 10. Choose prefix or postfix for each blank so the program prints 10 8 8.
Challenge 3
The magazine holds 30 bullets. Replace each 0 so that before gets the ammo count and then the ammo goes down by one, all in one expression, and after gets the ammo count after it goes down by one more. The program should print 30 28 28.