Home > Backend Development > C++ > Is Short-Circuit Evaluation Guaranteed in C and Java?

Is Short-Circuit Evaluation Guaranteed in C and Java?

Barbara Streisand
Release: 2024-11-09 09:05:02
Original
490 people have browsed it

Is Short-Circuit Evaluation Guaranteed in C   and Java?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template