0

I am pretty sure that this question has been asked before, but I really could not find it on stackoverflow. It seems relatively straightforward to me what the answer would be, but I need to be sure. I would be happy if you could redirect this question to any similar questions that you know of, that has already been answered (with good answers!). Here goes:

In the piece of code below

if (first_boolean && second_boolean && ... && last_boolean)
{
     //some code...
}

If, say the first boolean is false, would the compiler check any of the other boolean values if all those operators in between are AND operators? (Since, as you know, if all of those in between are AND operators, the whole boolean in the if statement would be false then). I am assuming the compiler checks all the logical operators beforehand (without evaluating the boolean statements) to make sure that if, say the first or second boolean is false, the whole statement would be false?

In addition, if the compiler does make such an optimization, does it check the whole boolean expression from left to right?

Thank in advance.

Konrad
  • 2,207
  • 4
  • 20
  • 31
  • 1
    http://en.wikipedia.org/wiki/Short-circuit_evaluation – user3528438 Apr 22 '15 at 21:21
  • 1
    The evaluation will stop -- or [short circuit](http://en.wikipedia.org/wiki/Short-circuit_evaluation) -- after the first true operand. And yes, like any expression, the compiler will interpret the whole thing before generating any code. – Paul Roub Apr 22 '15 at 21:21
  • 3
    Short-circuit evaluation should not be seen as an "optimization trick". On the opposite, it is an important language feature that allows you to write safe expressions like `i –  Apr 22 '15 at 21:23
  • @YvesDaoust Good point, although relying too often on this feature can lead to a bit obfuscated code. – Mateusz Grzejek Apr 22 '15 at 21:28
  • @MateuszGrzejek Practically any language feature can 'lead to a bit of obfuscated code'. 'You can write Fortran in any language' - D.M. Ritchie. – user207421 Apr 22 '15 at 21:30

0 Answers0