UMBC CS 201, Fall 98
Increment and Decrement Operators
It is so common to do things like:
total = total + 1; /* increment total */
that C provides a "shorthand" way of doing it:
total++; /* increment total */
++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.
Example:
x = 3;
printf("The value of X is %d\n", ++x); /* prints 4 */
/* and the value of x is now 4 */
printf("The value of X is %d\n", x++); /* prints 4 AGAIN */
/* 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
CSEE
|
201
|
201 F'98
|
lectures
|
news
|
help
Monday, 07-Sep-1998 15:03:06 EDT