C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – cout中的后增量行为大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > 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->
@H_419_43@

$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的评估未被排序(它们都没有在另一个之前排序).

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

@H_419_43@

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’产生副作用,正如我们上面所看到的,副作用是没有顺序的.

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

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

@H_419_43@

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和我们许多人获得大量投票(如果回答正确):)

大佬总结

以上是大佬教程为你收集整理的c – cout中的后增量行为全部内容,希望文章能够帮你解决c – cout中的后增量行为所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。