| [ directory ] |
|
8.5 The Increment and Decrement OperatorsThe ++ and -- operators increment and decrement their operands, respectively, by 1. These are unary operators. They can be used in both prefix and postfix mode. In prefix mode, the result of the operation is the value of the operand after it has been incremented or decremented; in postfix mode, the result of the operation is the value of the operand before it has been incremented or decremented. Listing 8.5 illustrates this point. Listing 8.5 Using the ++ and -- Operators (C#)
using System;
class Test {
public static void Main() {
double x;
x = 1.5;
Console.WriteLine(++x);
Console.WriteLine(--x);
Console.WriteLine(x++);
Console.WriteLine(x--);
Console.WriteLine(x);
}
}
The output of Listing 8.5 is as follows: 2.5 1.5 1.5 2.5 1.5 Initially the value of x is 1.5. The ++x increments the value first and then assigns it to the variable x, and hence 2.5 is printed as the first line. Similarly, --x decrements the value back to 1.5 and then assigns it to x, and hence 1.5 is printed. Then x++ increments the value of x after it is printed, and hence 1.5 is printed. Before x-- is executed, the value of x is 2.5. Executing x-- prints the value of x first and then decrements it by 1. The last line prints the value of x, which is now 1.5 (because of the preceding decrement, which took place after the value of x was printed). |
| [ directory ] |
|