Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...