我对这两个C语句有疑问:
x = y++;
t = *ptr++;
使用语句1,y的初始值被复制到x然后y递增。
使用语句2,我们查看* ptr指向的值,将其放入变量t,然后稍后增加ptr。
对于语句1,后缀增量运算符的优先级高于赋值运算符。因此,不应首先递增y,然后将x指定为递增的y?
值在这些情况下,我不理解运算符优先级。
答案 0 :(得分:5)
你误解了2]
的含义。后递增总是从递增之前产生值,然后在某个时间之后递增该值。
因此,t = *ptr++
基本上等同于:
t = *ptr;
ptr = ptr + 1;
同样适用于您的1]
- y++
产生的值是增量前y
的值。优先级不会改变这一点 - 无论表达式中其他运算符的优先级有多高或多低,它产生的值将始终是增量之前的值,并且增量将在之后的某个时间完成。
答案 1 :(得分:2)
预增量和后增量是内置的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
答案 2 :(得分: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
答案 3 :(得分:0)
后增量具有所有运算符的最低优先级。甚至低于赋值运算符。因此,当我们执行p=a++;
时,第一个值a
被分配给p
,而a
因此会增加。