Postfix (where the operator comes after the variable) increment/decrement return the value of the variable before the increment/decrement.
Prefix (where the operator comes before the variable) increment/decrement return the value of the variable after the increment/decrement.
All this assumes that those operators haven't been overloaded screwily. It may seem a bit backward, but it might help to think of it this way:
Postfix: Return the value of the variable, then increment/decrement.
Prefix: Increment/decrement, then return the value of the variable.
It's just user preference.
As long as nothing is being done with the return value of the operation, it doesn't matter.
Some may claim that ++n is more efficient because n++ technically creates a copy, but any decent compiler will turn both into the same operation, so just don't worry about this.
You can see that here using the Godbolt compiler explorer: https://godbolt.org/z/nx5NU_
Both end up just doing add ebx, 1 meaning 1 is added to a registry.
(Or, without optimization, both end up doing add DWORD PTR [rbp-8], 1, but it's the same assembly for both functions either way.)
If the variable is a custom class that overloads the ++ operator, then you might want to be more careful about it, because potentially logic might force a copy to be made. But probably not.
// Example program
#include <iostream>
void foo_A()
{
int n = 5;
int result = n++; // n gets incremented from 5 to 6, returns 5
std::cout << result << '\n';
}
void foo_B()
{
int n = 5;
int result = ++n; // n gets incremented from 5 to 6, returns 6
std::cout << result << '\n';
}
int main()
{
foo_A();
foo_B();
}
#include <iostream>
int main() {
int var = 1;
std::cout << ++var << std::endl; //Prints 2 (the value after the increment).
std::cout << var++ << std::endl; //Prints 2 (the value before the increment).
std::cout << var << std::endl; //Prints 3.
}
When you call n++, two things happen
(1) The value of n is returned, before n is incremented
(2) n itself is incremented by 1. This is "permanent". n will have a value of +1 after the operation.
When you call ++n, two things happen
(1) n is incremented by 1. Again, permanent.
(2) The value of n (now incremented by 1) is returned.