C ++代码显示不同,这是意外的,输出在不同的编译器 [英] C++ Code displays different, which is unexpected, output in different compilers

查看:169
本文介绍了C ++代码显示不同,这是意外的,输出在不同的编译器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个初学者问题。



以下是我正在使用的C ++代码

  int main(){
int x = 5,y = 5;
cout<< x--;
cout<<,;
cout<< - x;
cout<<,;
cout<< y - <<,< -y;
return 0;
}

在Turbo C ++ 3.0中运行时,下面是代码显示的输出:

  5,3,4,4 

在Windows上使用Code :: Blocks编译时(使用带有GCC / G ++的MinGW),以下是显示的输出:

  5,3,4,3 

以前,有时不同的编译器对某些问题的行为不同,但我不明白为什么会显示这个结果。从逻辑上来说,我认为输出应该是:

  5,3,5,3 


感谢您的支持,谢谢!你!

解决方案

没有正确或错误的输出。



原因在于C ++标准的第1.9.15(n3337)段(强调我的):


除非另有说明,否则对单个运算符的操作数和单个
表达式的子表达式的求值是无效的。
在程序的执行
期间多次评估的表达式,对其子表达式的未排序和不确定排序的评估不需要在不同的评估中一致地执行
。 -end note]
运算符的操作数的值计算在运算符结果的值计算之前排序。 如果对标量
对象的副作用相对于对同一标量对象的另一个副作用或使用相同标量对象的值的
值计算没有定义,则该行为不确定。


在此行

  cout<< y  - < ,< --y; 

您介绍了两个副作用(分别由postfix和prefix增量)和两个值计算在标量对象( y )上的 y - - y code>),在那里他们没有序列。



阅读更多关于这个此处


This is a beginners question.

Following is the C++ code that I was working with

int main() {
    int x=5, y=5;
    cout<<x--;
    cout<<",";
    cout<<--x;
    cout<<",";
    cout<<y--<<","<<--y;
    return 0;
}

When run in Turbo C++ 3.0 the following is the output displayed by the code:

5,3,4,4

When compiled with Code::Blocks on Windows (uses MinGW with GCC/G++) the following is the output displayed:

5,3,4,3

Previously, I have heard that sometimes different compilers behave differently to certain problems, but I don't understand why this result is being displayed. Since logically, as I think, the output should be:

5,3,5,3

Can you please tell me the reason for such output logically.

Thank you!

解决方案

There is no right or wrong output. Your code has undefined behavior and anything is possible.

The reason lies in paragraph 1.9.15 (n3337) of C++ standard (emphasis mine):

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [Note: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations. —end note ] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. 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.

In this line

cout << y-- << "," << --y;

you've introduced two side effects (increments by postfix and prefix, respectively) and two value computations (results of y-- and --y) on a scalar object (y) where they are unsequenced. Thus, your program is ill-formed and just about anything is a possible output.

Read more about this here.

这篇关于C ++代码显示不同,这是意外的,输出在不同的编译器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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