Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (17.99 KB, 2 trang )
Incrementing and Decrementing Variables
If you wanted to add 1 to a variable, you could use the + operator:
count = count + 1;
However, it is unlikely that an experienced programmer would write code like this.
Adding 1 to a variable is so common that in C#, you can do it with the ++ operator. To
increment the variable count by 1, write the following statement:
count++;
Similarly, subtracting 1 from a variable is so common that in C# you can do it with the ––
operator. To decrement the variable count by one, write this statement:
count ;
NOTE
The ++ and – – operators are unary operators, meaning that they take only a single
operand. Theyshare the same precedence and left associativity as the ! unary operator,
which is discussed in Chapter 4, “Using Decision Statements.”
The following table shows you how to use these two operators.
Don't write this Write this
variable = variable + 1; variable++;
variable = variable - 1; variable ;
Prefix and Postfix
The increment (++) and decrement (––) operators are unusual in that you can place them
either before or after the variable. Using the operator symbol before the variable is called
the prefix form of the operator, and using the operator symbol after the variable is called
the postfix form. Here are examples:
count++; // postfix increment
++count; // prefix increment
count ; // postfix decrement
count; // prefix decrement
Whether you use the prefix or postfix form of the ++ or –– operator makes no difference
to the variable being incremented or decremented. For example, if you write count++, the