Short-Circuit Evaluation in C and Java: Is It Guaranteed?
Short-circuit evaluation is a language feature that allows an expression to be evaluated partially, stopping once the result is known. This can significantly improve performance in certain circumstances.
Java's Short-Circuit Evaluation
In Java, the conditional expression if (a != null && a.fun()); benefits from short-circuit evaluation. When a is null, the condition will be false, and the expression a.fun() will not be evaluated. This saves the cost of potentially accessing a null reference.
C 's Short-Circuit Evaluation
In C , the conditional expression if (a != 0 && a->fun()); also implements short-circuit evaluation for built-in types like int and bool. This means that if a is zero, the expression a->fun() will not be evaluated.
Portability and Compilation
Short-circuit evaluation is guaranteed for built-in types in C across different platforms and compilers. However, it's important to note that overloading the && or || operators for custom types can disable short-circuited evaluation. This is because the compiler can't determine the behavior of the overloaded operators. As a result, overloading these operators is generally not recommended.
The above is the detailed content of Is Short-Circuit Evaluation Guaranteed in C and Java?. For more information, please follow other related articles on the PHP Chinese website!