Saturday, November 14, 2015

Short Circuit Expressions in C/C++ and Java

It was quite embarassing for me today. For more than 10 years since I started learning C language, I have not even heard of "short-circuit evaluation" until today. Today, I was studying a simple BinaryTree program in Java, and I encountered somewhat peculiar problem; I actually thought I found some sort of Java's fundamenetal error, but oh well. I was the culprit.

If you see a code below, what would you guess the output is?

public class ShortCircuit {
    private static boolean funcReturningTrue () {
        System.out.println ("this function returns true");
        return true;
    private static boolean funcReturningFalse () {
        System.out.println ("this function returns false");
        return false;
    public static void main (String[] args) {
        if (funcReturningTrue() || funcReturningFalse())
            System.out.println ("eval 1 complete");
        if (funcReturningFalse() && funcReturningTrue())
            System.out.println ("eval 2 complete");
        boolean bool = (true) ? funcReturningTrue() : funcReturningFalse();
        System.out.println ("bool = " + bool);

Well, I naively thought that both static methods inside if () evaluation would be called; I was wrong. It seems that there are some short-circuit implementation in order to save run time. For example, (true || bool) is evaluated to be true regardless of bool, so C/C++ and Java will not even evaluate bool. That is, only funcReturningTrue() will be called in the code above for the 1st if statement.

Similarly, (false && bool) is false regardless of bool, so again bool will not be evaluated. This corresponds to the 2nd if statement in the code above.

Lastly, the statement (condition) ? a : b will evaluate only a or b but not both depending on the condition. If one were to make sure that both conditions to be evaluated in the examples above, one should use | and & in place of || and &&.

Now, one can easily predict the output of the program above:
this function returns true
eval 1 complete
this function returns false
eval 2 complete
this function returns true
bool = true

No comments:

Post a Comment