操作员precedence为"<<"和" ++"在VS2008与优化 [英] Operator precedence for "<<" and "++" in VS2008 with optimization

查看:157
本文介绍了操作员precedence为"<<"和" ++"在VS2008与优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持一个奇怪的VS2008 C ++的问题,看起来像运营商precedence的不尊重。

I'm stuck with a weird VS2008 C++ issue, that looks like operator precedence is not respected.

我的问题是什么,它​​的输出:

My question is what is the output of this:

int i = 0;  
std::cout << ((i != 0) ? "Not zero " : "zero ") << ++i << std::endl;  

通常情况下, + 有precedence在&LT;&LT; ,对不对?或者是&LT;&LT; 认为像一个函数调用给它一个更高的precedence比 + ? 100%正确的标准答案是什么呢?

Normally the ++ has precedence over the <<, right? Or is the << considered like a function call giving it a higher precedence than the ++? What is the 100% correct standard answer to this?

要检查,我创建了一个新的空项目(VS2008控制台应用程序),在主贴仅此code和这里的结果:

To check, I created a new empty project (VS2008 console app), pasted only this code in the main and here are the results:

Debug|Win32: "zero 1"  
Release|Win32: "zero 1"  
Debug|x64: "zero 1"  
Release|x64: "Not zero 1"

顺便说一句,下面的例子中产生同样的结果:

Btw, the following example produces the exact same results:

i = 0;  
printf("%s %d\n", ((i != 0) ? "Not zero" : "zero"), ++i);  

和还改变释放的优化类型没有任何影响,但是禁用优化输出零1之类的配置。

And also changing the type of optimization in release has no effect, but disabling optimization outputs "zero 1" like other configurations.

推荐答案

这是无关的运营商precedence。
您正在使用&LT;&LT;这是语法糖函数调用:

This is nothing to do with operator precedence.
You are using << which is syntactic sugar for a function call:

std::cout << ((i != 0) ? "Not zero " : "zero ") << ++i << std::endl; 

// Equivalent too:

operator<<(operator<<(operator<<(std::cout, ((i != 0) ? "Not zero " : "zero ")), ++i), std::endl);

这里唯一的规则是,一个参数必须充分评价函数之前。有没有限制什么样的顺序中的参数进行评估,甚至如果他们的评价是交错电话(甚至部分计算)。

The only rule here is that a parameter must be fully evaluated before the function is called. There are no restrictions on what order the parameters are evaluated or even if their evaluation is interleaved with calls (or even partially evaluated).

1) ((i != 0) ? "Not zero " : "zero "))
2) ++i
3) operator<<(std::cout, (1));
4) operator<<((3), (2));
5) operator<<((4), std::endl);

国米pretation 2:

1) ++i
2) ((i != 0) ? "Not zero " : "zero "))
3) operator<<(std::cout, (2));
4) operator<<((3), (1));
5) operator<<((4), std::endl);

国米pretation 3:

1) ((i != 0) ? "Not zero " : "zero "))
2) operator<<(std::cout, (1));
3) ++i
4) operator<<((2), (3));
5) operator<<((4), std::endl);

在国米pretation 1展望作为参考:
必须施加的规则:

Looking at interpretation 1 as a reference:
The rules that must be applied:

 A) (1) happens before (3)
 B) (2) happens before (4)
 C) (3) happens before (4)
 D) (4) happens before (5)

这篇关于操作员precedence为&QUOT;&LT;&LT;&QUOT;和&QUOT; ++&QUOT;在VS2008与优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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