C语言中的后增量和前增量

5
我有关于以下两个C语句的问题:
1. x = y++;
2. t = *ptr++;
在第一种情况下,将y的初始值复制到x中,然后将y递增。在第二种情况下,我们查看*ptr指向的值,将其放入变量t中,然后稍后递增ptr。
对于语句1,后缀递增运算符的优先级高于赋值运算符。因此,y不应该先递增,然后将x分配给y的递增值吗?
我不理解这些情况下的运算符优先级。

1
如果您对此感到困惑,那么您可能需要阅读有关序列点的内容。 - Jeff Mercado
3个回答

6
你对2]的含义误解了。后缀自增运算符总是先返回自增前的值,然后再将其增加。
因此,t = *ptr++本质上等同于:
t = *ptr;
ptr = ptr + 1;

同样适用于您的1] - 从y++产生的值是增量之前的y的值。优先级不会改变这一点 - 无论表达式中其他运算符的优先级高低如何,它产生的值始终是增量之前的值,并且增量将在此之后完成。

看这个。正如我所说,指针会先被递增。http://c-faq.com/aryptr/ptrary2.html - Pkp
1
看看这个:"后缀++运算符的结果是操作数的值。在获得结果之后,操作数的值会增加。"(来自C99标准的§6.5.2.4/2)。 - Jerry Coffin
你是正确的。我以为我可以信任C-FAQ,遵循标准是最好的策略。抱歉。 - Pkp
1
@Pkp:我认为你误解了常见问题解答。那里所讨论的问题是“++”运算符是否应用于指针本身,还是指针所指向的内容(顺便提一下,这也是优先级在这种情况下所确定的)。答案是它应用于指针本身,而不是指针所指向的内容。 - Jerry Coffin

6

在 C 语言中,前缀和后缀自增运算符的区别:

前缀自增和后缀自增都是内置的 一元运算符。一元意味着:该函数只有一个输入。"运算符"的意思是:"对变量进行修改"。

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

在 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

0
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接