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

Ask the Expert - If/else or switch

WBOY
Release: 2024-07-16 06:27:39
Original
1123 people have browsed it

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!

source:dev.to
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template