?
This document uses PHP Chinese website manual Release
遞增/遞減運(yùn)算符是一元運(yùn)算符,用于將變量的值遞增/遞減1。
他們可以有后綴的形式:
expr ++ | ||
---|---|---|
expr -- |
以及前綴形式:
++ expr | ||
---|---|---|
-- expr |
前綴和后綴增量或減量的操作數(shù) expr 必須是整數(shù)類型(包括_Bool
和枚舉),實(shí)際浮點(diǎn)類型或指針類型的可修改左值。它可能是 cvr 限定的,不合格的或原子的。
后綴增量和減量運(yùn)算符的結(jié)果是 expr 的值。
前綴遞增運(yùn)算符的結(jié)果是將值添加1
到expr的值的結(jié)果:表達(dá)式++e
等同于e+=1
。前綴遞減運(yùn)算符的結(jié)果是1
從 expr 的值中減去該值的結(jié)果:該表達(dá)式--e
等同于e-=1
。
增量運(yùn)算符會(huì)啟動(dòng)將1
適當(dāng)類型的值添加到操作數(shù)的副作用。遞減運(yùn)算符啟動(dòng)1
從操作數(shù)中減去適當(dāng)類型值的副作用。與任何其他副作用一樣,這些操作在下一個(gè)序列點(diǎn)或之前完成。int a = 1; int b = a++; // stores 1+a (which is 2) to a // returns the value of a (which is 1) // After this line, b == 1 and a == 2 a = 1; int c = ++a; // stores 1+a (which is 2) to a // returns 1+a (which is 2) // after this line, c == 2 and a == 2
。
對(duì)任何原子變量進(jìn)行后增或后減是對(duì)存儲(chǔ)器順序 memory_order_seq_cst的原子讀取 - 修改 - 寫入操作。 | (自C11以來) |
---|
有關(guān)指針運(yùn)算的限制,請(qǐng)參閱算術(shù)運(yùn)算符以及應(yīng)用于操作數(shù)的隱式轉(zhuǎn)換。
由于涉及的副作用,必須謹(jǐn)慎使用增量和減量運(yùn)算符,以避免由于違反排序規(guī)則而導(dǎo)致的未定義行為。
遞增/遞減運(yùn)算符沒有為復(fù)數(shù)或虛數(shù)類型定義:加/減實(shí)數(shù)1的通常定義對(duì)虛數(shù)類型沒有影響,并且i
對(duì)于虛數(shù)使其增加/減少,但是1
對(duì)于復(fù)數(shù),它會(huì)使其處理0+yi
不同從yi
。
與C ++(以及C的某些實(shí)現(xiàn))不同,遞增/遞減表達(dá)式本身并不是左值:&++a
無效。
#include <stdlib.h>#include <stdio.h> int main(void) { int a = 1; int b = 1; printf("\n"); printf("original values: a == %d, b == %d\n", a, b); printf("result of postfix operators: a++ == %d, b-- == %d\n", a++, b--); printf("after postfix operators applied: a == %d, b == %d\n", a, b); // Reset a and b. a = 1; b = 1; printf("\n"); printf("original values: a == %d, b == %d\n", a, b); printf("result of prefix operators: ++a == %d, --b == %d\n", ++a, --b); printf("after prefix operators applied: a == %d, b == %d\n", a, b);}
輸出:
original values: a == 1, b == 1result of postfix operators: a++ == 1, b-- == 1after postfix operators applied: a == 2, b == 0 original values: a == 1, b == 1result of prefix operators: ++a == 2, --b == 0after prefix operators applied: a == 2, b == 0
C11 standard (ISO/IEC 9899:2011):
6.5.2.4 Postfix increment and decrement operators (p: 85)
6.5.3.1 Prefix increment and decrement operators (p: 88)
C99 standard (ISO/IEC 9899:1999):
6.5.2.4 Postfix increment and decrement operators (p: 75)
6.5.3.1 Prefix increment and decrement operators (p: 78)
C89/C90 standard (ISO/IEC 9899:1990):
3.3.2.4 Postfix increment and decrement operators
3.3.3.1 Prefix increment and decrement operators