2

I have seen a kind of "poetic" code in some code base. Though it looks straight forward, just want to confirm, if it's in right direction.
In a very simple form:

bool foo ();  
bool bar ();  

int main () {
  foo() or bar();  // <--- line
}

Is the code at highlighted line as good as below snippet?

if(foo() == false)
  bar();

I am aware of , operator where all the statements are invoked, but unsure about or (equivalent to ||) operator.
Testing in g++, it gives expected output.

4
  • 1
    Throw a few trigraphs in this and it makes that poem downright painful, btw. =P. Regardless, your question is about multi-part boolean short-circuit evaluation, and yes, exp1 || exp2 is nearly the same. The only thing missing is the unused exp2 result, which in both cases is thrown out anyway (if it is reached in the first place, which only happens with exp1 is zero-equivalent). Commented Aug 3, 2013 at 11:13
  • I am sorry @iammilind, but this is a dupe. Please next time make sure you google "C++ operators" or the like. Commented Aug 3, 2013 at 12:37
  • possible duplicate of How does C++ handle &&? (Short-circuit evaluation) Commented Aug 3, 2013 at 12:37
  • @H2CO3, I am aware of the short circuit evaluation. But I was concerned about the receiving of the value which is not happening here. Not sure if they are duplicates. Commented Aug 3, 2013 at 13:27

2 Answers 2

1

Yes, The or operator is the text equivalent of ||.

So what you said is correct.

Sign up to request clarification or add additional context in comments.

Comments

0

If the 1st condition is true the other one isn't evaluated anymore (in ||'s case) and therefore it's as you said:

if(foo() == false)
  bar();

The same thing applies to && when if the 1st condition is false, the second isn't evaluated anymore.

2 Comments

what if the second condition is false for &&. In &&, second condition is not evaluated if first is false.
sorry, it was a typo.. i meant the 1st is false. corrected answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.