“<<"的运算符优先级和“++"在 VS2008 中进行了优化 [英] Operator precedence for &quot;&lt;&lt;&quot; and &quot;++&quot; in VS2008 with optimization

查看:32
本文介绍了“<<"的运算符优先级和“++"在 VS2008 中进行了优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的 VS2008 C++ 问题,看起来操作符优先级没有得到尊重.

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;  

通常 ++ 优先于 <<,对吧?还是 << 被认为是一个函数调用,比 ++ 具有更高的优先级?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 控制台应用程序),只在 main 中粘贴了此代码,结果如下:

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
", ((i != 0) ? "Not zero" : "zero"), ++i);  

并且在 release 中更改优化类型也没有效果,但是像其他配置一样禁用优化输出零 1".

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

推荐答案

这与运算符优先级无关.
您正在使用 <<这是函数调用的语法糖:

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);

解释2:

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

解释 3:

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

以解释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)

这篇关于“<<"的运算符优先级和“++"在 VS2008 中进行了优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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