3

Possible Duplicate:
Why do we usually use || not |, what is the difference?

Example:

if(a && b && d)
{
...
}

I need to find out if a language supports checking all conditions in the if statement even if "b" fails. What is this concept called?

Community
  • 1
  • 1
ninjaneer
  • 6,741
  • 8
  • 59
  • 103

3 Answers3

14

No, neither Java nor C++ will evaluate d. This is short-circuit evaluation.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
  • 4
    Unless of course you overload `operator&&`. Then both are evaluated. What a nice, straightforward language ;) – chris May 24 '12 at 22:51
3

No, the binary logical operators are short-circuited. They evaluate their operands from left to right. If one of the operands evaluates such that the expression will be false then no other operands are evaluated.

Chris Hayden
  • 1,074
  • 5
  • 6
3

The standatd binary opeartions && and || are short-circuited. If you want to force both sides to evaluate, use & or | instead of && and ||. e.g.

public class StackOverflow {

   static boolean false1() {
      System.out.println("In false1");
      return false;
   }

   static boolean false2() {
      System.out.println("In false2");
      return false;
   }

   public static void main(String[] args) {
      System.out.println("shortcircuit");
      boolean b = false1() && false2();

      System.out.println("full evaluation");
      b = false1() & false2();
   }
}
user949300
  • 15,154
  • 6
  • 33
  • 65