后增量的行为 [英] Behavior of post increment in cout

查看:120
本文介绍了后增量的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;

main(){

int i = 5;

cout << i++ << i--<< ++i << --i << i << endl;


}

45555

以下程序:

int x=20,y=35;

x =y++ + y + x++ + y++;

cout << x<< endl << y;

结果为

126

37

输出。

推荐答案

cout << i++ << i--

在语义上等同于

operator<<(operator<<(cout, i++),   i--);
           <------arg1--------->, <-arg2->




$ 1.9 / 15-调用函数
无论该函数是否为
inline),每个值计算和
副作用与任何
参数表达式相关联,或与
后缀表达式指定
调用函数,在
执行每个表达式或
语句之前在被调用的
函数的正文中排序。[注意:值计算
和与$ b $相关的副作用b不同的参数表达式是
无序的。-end note
]

C ++ 0x:

这意味着arg1 / arg2参数的求值是无序的(它们都不在另一个之前排序)。

This means that the evaluation of the arguments arg1/arg2 are unsequenced (neither of them is sequenced before the other).

标准草案中的同一部分还规定

The same section in the draft Standard also states,


如果对标量对象的副作用是
,对同一标量对象
的另一个
副作用或使用同一标量对象的值
的值计算,
行为是未定义的。

If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

现在下面的完整表达式结尾处的分号处有一个序列点

Now there is a sequence point at the semicolon at the end of the full expression below

operator<<(operator<<(cout, i++), i--);
                                      ^ the interesting sequence point is right here

很明显,arg1和arg2导致对标量变量'i'的副作用,如上所述,副作用不受影响。

As is clear, evaluation of both arg1 and arg2 lead to side effect on the scalar variable 'i', and as we saw above, the side effects are unsequenced.

因此,代码具有未定义的行为。那么这是什么意思?

Therefore the code has undefined behavior. So what does that mean?

以下是在标准中定义未定义行为的方法。

Here is how 'undefined behavior' is defined :) in the Standard.


允许未定义的行为范围
从完全忽略情况
具有不可预测的结果到
在翻译或程序期间表现
以记录方式执行$ b环境
(有或没有发出
诊断消息)的特征的$ b,以终止
翻译或执行(用
发出诊断消息)。
许多错误的程序结构执行
不会产生未定义的行为;他们
需要被诊断。

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed.

你看到与@ DarkDust的响应相关'编译器甚至允许设置你的计算机起火: - )'

Do you see correlation with @DarkDust's response 'The compiler is even allowed to set your computer on fire :-)'

因此,从这样的代码中获得的任何输出都是在未定义的行为的可怕领域。

So any output you get from such a code is really in the dreaded realm of undefined behavior.

不要这样做。

只有定义它帮助OP和我们许多人得到大量的投票(如果回答正确):)

Only thing that is defined about such code is that it helps OP and many of us get lots of votes (if answered correctly) :)

这篇关于后增量的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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