Reputation: 398
How would one be able to emulate 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!
Upvotes: 0
Views: 31
Reputation: 79876
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.
Upvotes: 2