C++ Syntax: Increment: ++
Description
Possibly the most well known operator in C++; ++ is a unary operator that can
be applied to variables and increments the value they hold. For example often
for
loops have, as their increment-expr something like:-
counter++
that just adds one to counter.
Like all other C++ operators, ++ returns a value:-
- If ++ precedes the variable, e.g. ++counter, the value returned is the
value in counter after it has been incremented.
- If ++ follows the variable, e.g. counter++, the value returned is the
value in counter before it has been incremented.
This allows some C++ pedants to say that C++ is wrong, as it implies the
enhanced value isn't used, and that it should be called ++C.
Those who are less keen
on C++ argue that the name is right for the same reasons!
See operator
precedence
Other Uses for ++
None, although it might appear that there is a possible confusion with the
arithmetic +
operator followed a unary +. However C++ applies the rule that it always
takes the longest legal operator sequence, so ++ is interpreted as the
increment operator.
Usage Notes
Its best not to overuse the operator, and never apply it twice to the same
variable in the same statement, for example:-
my_int[index++] = index++;
is ambiguous as C++ is allowed to evaluate either ++ first.
Remember KISS = Keep It Simple Stupid!
Go Back to the
The C++ Crib Top Page
If you have any comments about this page please send them to
Nick West