Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c++ - Variable x equals a or b

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...