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

查看:25
本文介绍了为什么 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.
", a1, a2, b1, b2);

}

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

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: Annex 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天全站免登陆