UMBC CS 201, Fall 05
Increment and Decrement Operators
It is so common to write code like:
total = total + 1; /* increment total */
that C provides a "shorthand" way of doing it:
total++; /* increment total */
Pre-increment vs. Post-increment (or ++X vs. X++)
- ++X adds 1 to X.
- X++ adds 1 to X.
- The difference is in WHEN the
1 is added.
- If the pre-increment operator is being used, as in ++X,
X is incremented first and then that new value of X is used in any expression
that may be evaluated.
- If the post-increment operator is being used, as in X++, then the
expression is evaluated first (using the value of X), and then X is incremented
--X and X-- work the same way, except 1 is being subtracted from X.
x = 3;
/* prints 4 */
printf("The value of X is %d\n", ++x);
/* and the value of x is now 4 */
/* prints 4 AGAIN */
printf("The value of X is %d\n", x++);
/* but the value of x is now 5 */
Is all this a good idea?
- It's debatable
- ++ and -- are used a lot
- overuse can lead to obscure code
Sunday, 21-Aug-2005 09:53:19 EDT