变量x等于a或b [英] Variable x equals a or b

查看:158
本文介绍了变量x等于a或b的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是:

if(x == a || b){//do something}

与:

if(x == a || x == b){//do something}

?

我认为不是,因为在第一种情况下,我们评估x是否等于a,以及b是true还是false.

在第二种情况下,我们评估x是否等于a和x是否等于b.而且我了解到,在惰性评估中,如果x等于a,则我们将不进行进一步评估. /p>

但是有人认为在第一种情况下,我们问x是否等于a或b,所以我想确定.

解决方案

.

在C ++中,这是

:

x == a || b  // Same as (x == a) || b

等效于此:

(x == a) || (bool)b

如果xa相等,则

取值为true;如果将b转换为bool,则取值为true.另一方面,在C语言中,它等效于此:

(x == a) || (b != 0)

如果xa相等,或者如果b不同于0,则计算为true(在这里,我们必须隐式假设b是整数类型,否则不会)编译).

另一方面,这:

(x == a || x == b) // Same as ((x == a) || (x == b))

xa相等或xb相等时(即,如果x等于ab),

评估为true在C ++和C中都是如此.

Is this:

if(x == a || b){//do something}

same as:

if(x == a || x == b){//do something}

?

I think it is not, because in the first case we evaluate if x equals a and if b is true or false.

In the second case, we evaluate if x equals a and if x equals b. And I understand that in the lazy evaluation if x equals a than we are not evaluating further.

But somebody thinks that in the first case we ask if x equals a or b, so I wanna make sure.

解决方案

No.

In C++, this:

x == a || b  // Same as (x == a) || b

Is equivalent to this:

(x == a) || (bool)b

Which evaluates to true if x and a are equal OR if b evaluates to true when converted to bool. In C, on the other hand, it is equivalent to this:

(x == a) || (b != 0)

Which evaluate to true if x and a are equal OR if b is different from 0 (here we must make the implicit assumption that b is of integral type, otherwise this won't compile).

On the other hand, this:

(x == a || x == b) // Same as ((x == a) || (x == b))

Evaluates to true when either x and a are equal OR x and b are equal (i.e., if x is either equal to a or equal to b) both in C++ and in C.

这篇关于变量x等于a或b的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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