Home  >  Article  >  Java  >  Ask the Expert - If/else or switch

Ask the Expert - If/else or switch

WBOY
WBOYOriginal
2024-07-16 06:27:391089browse

Pergunte ao especialista - If/else ou switch

Under what conditions should I use an if-else-if ladder instead of a switch when coding a multipath branch?

Answer:
In general, use an if-else-if ladder when the conditions controlling the selection process do not depend on a single value.

Example:

if(x < 10) // ...
else if(y != 0) // ...
else if(!done) // ...

This sequence cannot be recoded with a switch because all three conditions involve different variables – and different types. What variable would control the switch?
You will also have to use an if-else-if ladder when testing floating point values ​​or other objects that are not valid types in a switch expression.

The above is the detailed content of Ask the Expert - If/else or switch. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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