C中的后增量和前增量

我对这两个C语句有疑问:

  1. x = y++;

  2. t = *ptr++;

使用语句1,y的初始值被复制到x然后y递增。

使用语句2,我们查看* ptr指向的值,将其放入变量t,然后稍后增加ptr。

对于语句1,后缀增量运算符的优先级高于赋值运算符。 所以不应该首先递增y,然后将x赋值给y的递增值?

在这些情况下,我不理解运算符优先级。

你错了你的意思2] 。 后递增总是从递增之前产生值,然后在某个时间之后递增该值。

因此, t = *ptr++基本上相当于:

 t = *ptr; ptr = ptr + 1; 

这同样适用于你的1] – 从y++产生的值是增量前的y值。 优先级不会改变 – 无论表达式中其他运算符的优先级有多高或多低,它产生的值将始终是增量之前的值,并且增量将在之后的某个时间完成。

C中的预增量和后增量之间的差异:

预增量和后增量是内置的一元运算符 。 一元意味着:“具有一个输入的function”。 “运算符”表示:“对变量进行修改”。

内置的一元运算符的增量(++)和减量( – )修改它们所附加的变量。 如果您尝试对常量或文字使用这些一元运算符,则会出现错误。

在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 
 int rm=10,vivek=10; printf("the preincrement value rm++=%d\n",++rmv);//the value is 11 printf("the postincrement value vivek++=%d",vivek++);//the value is 10 

后增量具有所有运算符的最低优先级。 甚至低于赋值运算符。 所以当我们做p=a++; 第一个值a被分配给p ,而a则递增。