C 中前置增量和后置增量的区别:
前置增量和后置增量是内置的Unary Operators。一元的意思是:“一个输入的函数”。 “运算符”的意思是:“对变量进行了修改”。
自增 (++) 和自减 (--) 内置一元运算符会修改它们附加到的变量。如果您尝试对常量或文字使用这些一元运算符,则会收到错误消息。
在 C 中,这里是所有内置一元运算符的列表:
Increment: ++x, x++
Decrement: −−x, x−−
Address: &x
Indirection: *x
Positive: +x
Negative: −x
Ones_complement: ~x
Logical_negation: !x
Sizeof: sizeof x, sizeof(type-name)
Cast: (type-name) cast-expression
这些内置运算符是变相的函数,它们接受变量输入并将计算结果放回到同一个变量中。
后增量示例:
int x = 0; //variable x receives the value 0.
int y = 5; //variable y receives the value 5
x = y++; //variable x receives the value of y which is 5, then y
//is incremented to 6.
//Now x has the value 5 and y has the value 6.
//the ++ to the right of the variable means do the increment after the statement
预增量示例:
int x = 0; //variable x receives the value 0.
int y = 5; //variable y receives the value 5
x = ++y; //variable y is incremented to 6, then variable x receives
//the value of y which is 6.
//Now x has the value 6 and y has the value 6.
//the ++ to the left of the variable means do the increment before the statement
后递减示例:
int x = 0; //variable x receives the value 0.
int y = 5; //variable y receives the value 5
x = y--; //variable x receives the value of y which is 5, then y
//is decremented to 4.
//Now x has the value 5 and y has the value 4.
//the -- to the right of the variable means do the decrement after the statement
预减量示例:
int x = 0; //variable x receives the value 0.
int y = 5; //variable y receives the value 5
x = --y; //variable y is decremented to 4, then variable x receives
//the value of y which is 4.
//x has the value 4 and y has the value 4.
//the -- to the right of the variable means do the decrement before the statement