ptg7068951
All About Operators 57
This statement reduces yby one.
You also can put the increment and decrement operators in front of the
variable name, as in the following statements:
++x;
--y;
Putting the operator in front of the variable name is calledprefixing, and
putting it after the name is called postfixing.
The difference between prefixed and postfixed operators becomes impor-
tant when you use the increment and decrement operators inside an
expression.
Consider the following statements:
int x = 3;
int answer = x++ * 10;
What does the answervariable equal after these statements are handled?
You might expect it to equal 40—which would be true if 3 was increment-
ed by 1, which equals 4, and then 4 was multiplied by 10.
However, answerends up with the value 30 because the postfixed operator
was used instead of the prefixed operator.
When a postfixed operator is used on a variable inside an expression, the
variable’s value doesn’t change until after the expression has been com-
pletely evaluated. The statement int answer = x++ * 10does the same
thing in the same order, as the following two statements:
int answer = x * 10;
x++;
The opposite is true of prefixed operators. If they are used on a variable
inside an expression, the variable’s value changes before the expression is
evaluated.
Consider the following statements:
int x = 3;
int answer = ++x * 10;
This does result in the answervariable being equal to 40. The prefixed
operator causes the value of the xvariable to be changed before the expres-
sion is evaluated. The statement int answer = ++x * 10does the same
thing in order, as these statements:
NOTE
Confused yet? This is easier
than it sounds,if you think back
to elementary school when you
learned about prefixes. Just as
a prefix such as “sub-” or “un-”
goes at the start of a word,a
prefix operator goes at the start
of a variable name. A postfix
operator goes at the end.