本文介绍了为什么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:

您可以查找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 ++相同的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 07:56
查看更多