Incrementing and decrementing are such common operations that C++
special operators for them. The
operator adds one to the current value of an int, char or double, and
subtracts one. Neither operator works on a
, and neither should be used on a
Technically, it is legal to increment a variable and use it in an
the same time. For example, you might see something like:
ShowText ( iX++ );
Looking at this, it is not clear whether the increment will take effect
after the value is displayed. Because expressions like this tend to be
confusing, I would discourage you from using them. In fact, to
discourage you even more, I’m not going to tell you what the result is.
If you really want to know, you can try it.
We can rewrite
void CountDown (
int iN )
while ( iN > 0 )
ShowText ( iN );
ShowText ( "START!!!" );
It is a common error to
write something like
iN = iN++; // WRONG!!
Unfortunately, this is syntactically legal, so the compiler will not
warn you. The
effect of this statement is to leave the value of iN unchanged (which
should give you a hint as to the answer to the earlier question). This
is often a difficult bug to track down.
Remember, you can write
iN = iN +1;
or you can write
but you shouldn’t mix them.