简体   繁体   中英

Using "?:" to emulate short-circuit evaluation

How would one be able to emulate foo() || bar() foo() || bar() and foo() && bar() using short-circuiting and the ?: operator?

I'm a student and have never used the ?: operator and would like to try. After doing some Googling I've found out that it's essentially:

Condition ? (things to do if true) : (things to do if false);

Would this be possible to achieve without using && and || ? I'm trying to get a grip on short-circuiting, as I'm very new to it and finals are coming up!

Assuming foo() and bar() both return boolean , then

foo() || bar()

is the same as

foo() ? true : bar();

because foo() is evaluated first, and bar() only needs to be evaluated if foo() is false.

Likewise,

foo() && bar()

is the same as

foo() ? bar() : false;

foo() is evaluated first, and bar() only needs to be evaluated if foo() is true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM