As far as I understand, a++ is postfix incrementation, it adds 1 to a and returns the original value. ++a is prefix incrementation, it adds 1 to a ad returns the new value.
I wanted to try this out, but in both cases, it returns the new value. What am I misunderstanding?
#include <stdio.h>
int main() {
int a = 0;
int b = 0;
printf("%d\n", a); // prints 0
printf("%d\n", b); // prints 0
a++; // a++ is known as postfix. Add 1 to a, returns the old value.
++b; // ++b is known as prefix. Add 1 to b, returns the new value.
printf("%d\n", a); // prints 1, should print 0?
printf("%d\n", b); // prints 1, should print 1
return 0;
}
Remember, C and C++ are somewhat expressive languages.
That means most expressions return a value. If you don't do anything with that value, it's lost to the sands of time.
The expression
will return
a
's former value. As mentioned before, if its return value is not used right then and there, then it's the same aswhich returns the new value.
The above statements will work as you expect, since you're using the expressions right there.
The below would also work.