为什么a =(b ++)具有与a = b ++相同的行为? [英] Why does a=(b++) have the same behavior as a=b++?

查看:111
本文介绍了为什么a =(b ++)具有与a = b ++相同的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C编写一个小型测试应用程序,并在我的Ubuntu 14.04上预安装了GCC 4.8.4.我对表达式a=(b++);的行为与a=b++;相同的事实感到困惑.使用以下简单代码:

I am writing a small test app in C with GCC 4.8.4 pre-installed on my Ubuntu 14.04. And I got confused for the fact that the expression a=(b++); behaves in the same way as a=b++; does. The following simple code is used:

#include <stdint.h>
#include <stdio.h>

int main(int argc, char* argv[]){
    uint8_t a1, a2, b1=10, b2=10;
    a1=(b1++);
    a2=b2++;

    printf("a1=%u, a2=%u, b1=%u, b2=%u.\n", a1, a2, b1, b2);

}

gcc编译后的结果为a1=a2=10,而b1=b2=11.但是,我希望括号将b1递增,然后将其值分配给a1.

The result after gcc compilation is a1=a2=10, while b1=b2=11. However, I expected the parentheses to have b1 incremented before its value is assigned to a1.

即,a1应该为11,而a2等于10.

有人知道这个问题吗?

推荐答案

引用自C99:6.5.2.4:

Quoting from the C99:6.5.2.4:

后缀++运算符的结果是操作数的值. 获得结果后,操作数的值将递增. (即,将适当类型的值1添加到其中.)请参见 的加法运算符和化合物赋值的讨论 有关约束,类型和转换及其影响的信息 对指针的操作.更新存储值的副作用 的操作数应出现在上一个和下一个序列之间 点.

The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented. (That is, the value 1 of the appropriate type is added to it.) See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The side effect of updating the stored value of the operand shall occur between the previous and the next sequence point.

您可以查找C99:附件C以了解有效的序列点是什么.

You can look up the C99: annex C to understand what the valid sequence points are.

在您的问题中,仅添加一个括号并不会更改顺序点,只有;字符会更改该顺序点.

In your question, just adding a parentheses doesn't change the sequence points, only the ; character does that.

或者换句话说,您可以像查看b的临时副本一样查看它,并且副作用是原始的b递增.但是,直到到达序列点,所有评估都在b的临时副本上完成.然后,b的临时副本将被丢弃,当到达序列点时,副作用(即增量操作)将提交到存储中.

Or in other words, you can view it like there's a temporary copy of b and the side-effect is original b incremented. But, until a sequence point is reached, all evaluation is done on the temporary copy of b. The temporary copy of b is then discarded, the side effect i.e. increment operation is committed to the storage,when a sequence point is reached.

这篇关于为什么a =(b ++)具有与a = b ++相同的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆