The Truth About Increments

There is an important difference betwen the prefix and postfix versions of the increment operator, for instance, between ++i and i++. Both will increment i, but they differ in the value produced by the expression. When the value is not used, they are the same, so the statements ++i; and i++; are identical. They differ when the value is used, often in a test.

When an expression operator does something more than produce a value, that extra work is called a side effect. The expressions ++i and i++ have different values but the same side-effect.

#include <iostream> using namespace std; int main() { int fred = 14; int joe = 42; int alex = 0; alex = fred++; cout << "A: alex=" << alex << ", fred=" << fred << endl; alex = ++joe; cout << "B: alex=" << alex << ", joe=" << joe << endl; fred = 18; joe = 25; alex = --fred; cout << "C: alex=" << alex << ", fred=" << fred << endl; alex = joe--; cout << "D: alex=" << alex << ", joe=" << joe << endl; cout << "And now: " << alex++ + --fred * ++joe << endl; }