1

As the evaluation of logical operators && and || are defined as "short circuit", I am assuming the following two pieces of code are equivalent:

p = c || do_something();

and

if (c) {
   p = true;
}
else {
   p = do_something();
}

given p and c are bool, and do_something() is a function returning bool and possibly having side effects. According to the C standard, can one rely on the assumption the snippets are equivalent? In particular, having the first snippet, is it promised that if c is true, the function won't be executed, and no side effects of it will take place?

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
  • 2
    Check out http://stackoverflow.com/questions/3958864/c-is-there-lazy-evaluation-when-using-operator-as-in-c – tonysdg Jul 15 '15 at 17:27
  • That's pretty much what short circuiting is all about. And it is guaranteed by the standards ONLY when the operation is between `bool`. NOT when the operator is overloaded. – spalac24 Jul 15 '15 at 17:54
  • @user3267581 What do you mean by overloaded operator? Are you having *C++* in mind? – Eugene Sh. Jul 15 '15 at 17:55
  • Yes, sorry, didn't notice the question was C specific. – spalac24 Jul 15 '15 at 17:59
  • I believe in C++ it should be possible for an overloaded `||` be implemented as short circuited as well.. But it's a different question – Eugene Sh. Jul 15 '15 at 18:02

2 Answers2

2

After some search I will answer my question myself referencing the standard: The C99 standard, section 6.5.14 Logical OR operator is stating:

Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to 0, the second operand is not evaluated.

And a similar section about &&. So the answer is yes, the code can be safely considered equivalent.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
1

Yes, you are correct in your thinking. c || do_something() will short-circuit if c is true, and so will never call do_something().

However, if c is false, then do_something() will be called and its result will be the new value of p.

Jashaszun
  • 9,207
  • 3
  • 29
  • 57