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