|
|
Operators and Assignments - Prefix and Postfix Operators
- the operators ++ and -- are used to increment or decrement a variable value by 1
- binary numeric promotion is applied on both the 1 and the variable value before the addition or subtraction occurs (ie at a minimum both values are promoted to an int) BUT the type of the expression is the type of the variable so narrowing conversion is applied if necessary ie if the original variable is a byte, short, or char the result is narrowed to the corresponding type
byte b = 2;
byte b1;
b1 = ++b; // no error although promotion occurs
b = 127;
b1 = ++b; // result: -128 (no error as fits within byte type)
- the expression has the same type as the variable
- they can appear before a variable (prefix) or after a variable (postfix)
- cannot be used with final variables
Prefix (++x) and Postfix (x++) increment operators
Prefix (--x) and Postfix (x--) decrement operators
Using prefix and postfix operators in expressions
- when a prefix expression (++x or --x) is used as part of an expression, the value returned is the value calculated after the prefix operator is applied
int x = 0;
int y = 0;
y = ++x; // result: y=1, x=1
x is incremented by 1 and the result is assigned to y
- when a postfix expression (x++ or x--) is used as part of an expression, the value returned is the value calculated before the postfix operator is applied
int x = 0;
int y = 0;
y = x++; // result: y=0, x=1
original value of x is stored, x is incremented,
original value of x is assigned to y
- when using the postfix form of the operators do not try constructs like
int x = 0;
x = x++; // result: 0, x is not incremented
original value of x is saved (x0rig)
x is incremented
x0rig is assigned to x
therefore, x will always equal original value
Effect on 'char' type
Example Code
Tips
- postfix/prefix operators have the highest level of precedence
- remember that when the postfix operator is used in an expression, the current value of the variable is used
|