0

Possible Duplicate:
Is Short Circuit Evaluation guaranteed In C++ as it is in Java?
How does C++ handle &&? (Short-circuit evaluation)

I have the following struct definition and a particular use case:

struct foo
{
   bool boo;
};

int main()
{
  foo* f = 0;
   .
   .
   .
  if ((f) && (f->boo)) // <--- point of contention
   return 0
  else
   return 1;
}

Does the standard guarantee that the first set of braces in the if-statement above will always be evaluated before the second?

If it doesn't what is the best what to rewrite the above bit of code?

Currently I have the following mess:

if (f)
{
   if (f->boo)
      return 0;
   else
      return 1;
}
else
   return 1;
Community
  • 1
  • 1
Soda Coader
  • 101
  • 12
  • Yes, that's the point of short-circuiting. – Mysticial Jul 12 '12 at 00:46
  • Please update the question so that the two code segments agree; the `main()` version returns 0 in the first case but the 2nd example returns 1 in the first case. – Kevin Grant Jul 12 '12 at 00:51
  • @KevinGrant: No need to update; the question has been closed as an exact duplicate, and answer is clear. – Keith Thompson Jul 12 '12 at 00:52
  • I want to mention two things: The first is mentioned in a link: If you overload `operator&&` or `operator||`, it will lose its short-circuit nature. The second is that `&` and `|` work, and are not short-circuited, if you desire non-short-circuited behaviour. – chris Jul 12 '12 at 01:32
  • @chris: But `&` and `|`, when applied to integer operands are bitwise, not logical. I suppose you could cast each operand to `bool` if you want non-short-circuit logical "and" and "or" operators. – Keith Thompson Jul 12 '12 at 03:05
  • @KeithThompson, True, it should be within a boolean context. – chris Jul 12 '12 at 03:10
  • @chris: Then again, how often do you *need* non-short-circuit behavior? – Keith Thompson Jul 12 '12 at 03:17
  • @KeithThompson, Very good point. Both of those points were small things that are helpful to remember, but not prominent at all. – chris Jul 12 '12 at 03:18

2 Answers2

5

Yes, it's guaranteed -- and the parentheses are unnecessary.

Both && and || are short-circuit operators; they evaluate the left operand, then evaluate the right operand only if it's needed to determine the result.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
5

It may be a matter of style but you could say:

return (f && f->boo);

...or to be slightly more explicit:

return ((f && f->boo) ? 1 : 0);
Kevin Grant
  • 5,363
  • 1
  • 21
  • 24