VS2008 c ++编译器会优化以下if语句吗? [英] Would VS2008 c++ compiler optimize the following if statement?

查看:315
本文介绍了VS2008 c ++编译器会优化以下if语句吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if (false == x) { ...}

而不是:

if (!x) { ... }

if (false == f1()) { ...}

,而不是:

if (!f1()) { ... }

我认为if(false == ...版本是更可读的,你同意,还是有另一个可以提出的窍门?它会一样快?谢谢。

I think the if(false == ... version is more readable. Do you agree, or have another trick you can propose? Will it be just as fast? Thanks.

这就是为什么我不喜欢!x:

This is why I do not like !x:

if (25 == a->function1(12345, 6789) &&
    45 == b->function1(12345, 6789) &&
    !c->someOtherFunction(123)) { ... }

以下似乎更好:

if (25 == a->function1(12345, 6789) &&
    45 == b->function1(12345, 6789) &&
    false == c->someOtherFunction(123)) { ... }


推荐答案

一个好的编译器应该为两个代码块生成相同的代码。

A good compiler should generate the same code for both code blocks.

false == f1()与!f1(),你应该更担心这个例子中的短路评估: / p>

However, instead of worrying about false == f1() vs. !f1(), you should be way more worried about the short-circuit evaluation in this example:

if (25 == a->function1(12345, 6789) &&
    45 == b->function1(12345, 6789) &&
    !c->someOtherFunction(123)) { ... }

某些编译器将生成跳过执行 b-> function1() c-> someOtherFunction() ,如果 a-> function1()调用发生在不同于25的调用 - 原因是,编译器已经知道整个结果 if()语句,所以它可以跳到正确的地方。

Certain compilers will generate code that will skip the execution of b->function1() and c->someOtherFunction(), if a->function1() call happens to evaluate to something different than 25 - the reason being, the compiler already knows the outcome of the whole if () statement at that point, so it can jump at the right place.

如果你的代码依赖于被修改的状态任何跳过的功能,你可能会得到令人讨厌的惊喜。

If your code depends on a state being modified by any of the skipped functions, you might get nasty surprises.

这篇关于VS2008 c ++编译器会优化以下if语句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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