逻辑比较:从左到右的评估是否保证? [英] Logical comparisons: Is left-to-right evaluation guaranteed?

查看:233
本文介绍了逻辑比较:从左到右的评估是否保证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否保证逻辑比较运算符(&& || )的从左到右评估?

Is left-to-right evaluation of logical comparison operators (&& ||) guaranteed?

假设我有这个:

SDL_Event event;

if (SDL_PollEvent(&event)) {
    if (event.type == SDL_QUIT) {
            // do stuff
    }
}

这是否保证与此相同?

SDL_Event event;

if (SDL_PollEvent(&event) && event.type == SDL_QUIT) {
    // do stuff
}

这也很重要,假设我们有两个要求: a code> b 。需求 a 更有可能失败,然后 b 。然后,如果(a& b)比 if(b& a)

This can also be very important, let's say we have two requirements, a and b. Requirement a is much more likely to fail then b. Then it's more efficient to say if (a && b) than if (b && a).

推荐答案

是的,这是保证的,否则这样的操作员会失去很多用处。

Yes, it's guaranteed, otherwise such operators would lose much of their usefulness.

相关标准报价:

§5.14¶1


& &&& 右对照评估:如果第一个操作数 false ,则不评估第二个操作数。

Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

§5.15¶1


不同于 | || 保证从左到右的评估;此外,如果第一操作数计算 true ,则不评估第二操作数。

Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.

这篇关于逻辑比较:从左到右的评估是否保证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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