Increment and Decrement Operators增量和減量運(yùn)算符

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

程序員,自然地,知道一種最普通的帶有數(shù)字變量的運(yùn)算符,用來實(shí)現(xiàn)加1或者減1。Java步C和C++的后塵,也有增量和減量運(yùn)算符:n++ 給當(dāng)前變量的值加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改變?yōu)?3。由于這些運(yùn)算符用來改變變量的值,所以他們不能被用來改變數(shù)字本身。例如4++就不是一個(gè)合法的語句。

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.

這些運(yùn)算符實(shí)際上有兩種形式;你見過運(yùn)算符被置于操作數(shù)后面的“后綴”形式。還有一個(gè)前綴形式,++n。都是改變變量的值多一或少一。二者的不同僅體現(xiàn)在他們用于表達(dá)式的時(shí)候。前綴形式先做加法運(yù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.

我們不推薦在其他表達(dá)式中使用++,因?yàn)檫@經(jīng)常導(dǎo)致混亂的代碼以及惱人的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.")

(當(dāng)然,當(dāng)++運(yùn)算符賦予C++語言這個(gè)名字的時(shí)候,它也引發(fā)了這個(gè)語言的第一個(gè)笑話。C++的反對(duì)者指出就連這個(gè)程序語言的名字都存在bug:“畢竟,她真的該叫做C++,因?yàn)槲覀冎幌朐谡Z言被改進(jìn)以后使用它。”)


文章來源:http://x-spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!309.entry