3

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

  1. x = y++;

  2. t = *ptr++;

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

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

对于语句 1,后缀自增运算符的优先级高于赋值运算符。那么不应该先增加y,然后将x分配给y的增加值吗?

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

4

3 回答 3

6

你误解了你的意思2]。后增量总是从增量之前产生值,然后在之后的某个时间增加值。

因此,t = *ptr++本质上等价于:

t = *ptr;
ptr = ptr + 1;

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

于 2012-05-26T06:45:42.043 回答
5

C中前置增量和后置增量的区别:

前置增量和后置增量是内置的一元运算符。一元表示:“具有 ONE 输入的函数”。“运算符”的意思是:“对变量进行了修改”。

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

在 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
于 2013-07-23T19:16:14.410 回答
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
于 2014-10-09T08:23:29.250 回答