Auto increment and decrement
C, and therefore C++, is full of
shortcuts. Shortcuts can make code much easier to type, and sometimes much
harder to read. Perhaps the C language designers thought it would be easier to
understand a tricky piece of code if your eyes didn’t have to scan as
large an area of print.
One of the nicer shortcuts is the
auto-increment and auto-decrement
operators. You often use these to change loop variables, which control the
number of times a loop executes.
The
auto-decrement operator is ‘--’ and means “decrease by
one unit.” The auto-increment operator is ‘++’ and
means “increase by one unit.” If A is an int, for
example, the expression ++A is equivalent to (A = A + 1).
Auto-increment and auto-decrement operators produce the value of the variable as
a result. If the operator appears before the variable, (i.e., ++A), the
operation is first performed and the resulting value is produced. If the
operator appears after the variable (i.e. A++), the current value is
produced, and then the operation is performed. For example:
//: C03:AutoIncrement.cpp
// Shows use of auto-increment
// and auto-decrement operators.
#include <iostream>
using namespace std;
int main() {
int i = 0;
int j = 0;
cout << ++i << endl; // Pre-increment
cout << j++ << endl; // Post-increment
cout << --i << endl; // Pre-decrement
cout << j-- << endl; // Post decrement
} ///:~
If you’ve been wondering about the
name “C++,” now you understand. It implies
“one step beyond
C.”