加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – cout中的后增量行为

发布时间:2020-12-16 10:50:28 所属栏目:百科 来源:网络整理
导读:参见英文答案 Why are these constructs using pre and post-increment undefined behavior?????????????????????????????????????14个 #include iostreamusing namespace std;main(){int i = 5;cout i++ i-- ++i --i i endl;} 用g编译的上述程序给出了输出
参见英文答案 > Why are these constructs using pre and post-increment undefined behavior?????????????????????????????????????14个

#include <iostream>
using namespace std;

main(){

int i = 5;

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


}

用g编译的上述程序给出了输出:

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- “When calling a function
(whether or not the function is
inline),every value computation and
side effect associated with any
argument expression,or with the
postfix expression designating the
called function,is sequenced before
execution of every expression or
statement in the body of the called
function. [ Note: Value computations
and side effects associated with
different argument expressions are
unsequenced. —end note
]

C 0x:

这意味着对参数arg1 / arg2的评估未被排序(它们都没有在另一个之前排序).

标准草案中的同一部分也指出,

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.

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

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

很明显,对arg1和arg2的评估都会对标量变量’i’产生副作用,正如我们上面所看到的,副作用是没有顺序的.

因此代码具有未定义的行为.那是什么意思呢?

以下是标准中“未定义行为”的定义方式:).

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响应的关联’甚至允许编译器将您的计算机置于火上:-)’

因此,从这样的代码中获得的任何输出实际上都处于未定义行为的可怕领域.

不要这样做.

关于此类代码的唯一定义是它有助于OP和我们许多人获得大量投票(如果回答正确):)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读