Increment and Decrement Operators增量和减量运算符
Programmers, of course, know that one of the most common operations with a numeric variable is to add or subtract 1. Java, following in the footsteps of C and C++, has both increment and decrement operators: n++ adds 1 to the current value of the variable n, and n-- subtracts 1 from it. For example, the code
程序员,自然地,知道一种最普通的带有数字变量的运算符,用来实现加1或者减1。Java步C和C++的后尘,也有增量和减量运算符:n++ 给当前变量的值加1,而n-- 从n中减去1。例如,代码:
int n = 12;
n++;
changes n to 13. Because these operators change the value of a variable, they cannot be applied to numbers themselves. For example, 4++ is not a legal statement.
将n改变为13。由于这些运算符用来改变变量的值,所以他们不能被用来改变数字本身。例如4++就不是一个合法的语句。
There are actually two forms of these operators; you have seen the "postfix" form of the operator that is placed after the operand. There is also a prefix form, ++n. Both change the value of the variable by 1. The difference between the two only appears when they are used inside expressions. The prefix form does the addition first; the postfix form evaluates to the old value of the variable.
这些运算符实际上有两种形式;你见过运算符被置于操作数后面的“后缀”形式。还有一个前缀形式,++n。都是改变变量的值多一或少一。二者的不同仅体现在他们用于表达式的时候。前缀形式先做加法运算;后缀形式求得变量的原值。
int m = 7;
int n = 7;
int a = 2 * ++m; // now a is 16, m is 8
int b = 2 * n++; // now b is 14, n is 8
We recommend against using ++ inside other expressions because this often leads to confusing code and annoying bugs.
我们不推荐在其他表达式中使用++,因为这经常导致混乱的代码以及恼人的bug。
(Of course, while it is true that the ++ operator gives the C++ language its name, it also led to the first joke about the language. C++ haters point out that even the name of the language contains a bug: "After all, it should really be called ++C, because we only want to use a language after it has been improved.")
(当然,当++运算符赋予C++语言这个名字的时候,它也引发了这个语言的第一个笑话。C++的反对者指出就连这个程序语言的名字都存在bug:“毕竟,她真的该叫做C++,因为我们只想在语言被改进以后使用它。”)
文章来源:
http://x-spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!309.entry