Why is the switch sentence better than the if sentence in C++
This article mainly explains "why the switch statement is better than the if statement in C++". The explanation in this article is simple and clear, easy to learn and understand. Please follow the idea of Xiaobian slowly and deeply to study and learn "why the switch statement is better than the if statement in C++" together.
ES.70: Switch statements are better than if statements when making selections
Reason
Readability.
readability
Efficiency: A switch compares against constants and is usually better optimized than a series of tests in an if-then-else chain.
Efficiency: The time-constant comparison operations performed by switch statements are usually better optimized than a series of if-then-else statements.
A switch enables some heuristic consistency checking. For example, have all values of an enum been covered? If not, is there a default?
The switch statement allows certain heuristics to check. For example, are all values of enumeration types covered? If not, is the default option set?
Example
void use(int n)
{
switch (n) { // good
case 0:
// ...
break;
case 7:
// ...
break;
default:
// ...
break;
}
}
rather than (rather than):
void use2(int n)
{
if (n == 0) // bad: if-then-else chain comparing against a set of constants
// ...
else if (n == 7)
// ...
}
Enforcement
Flag if-then-else chains that check against constants (only).
An if-then-else decision chain comparing a tag to a constant value (only in this case)
Thank you for reading, the above is "C++ why switch statement is better than if statement" content, after the study of this article, I believe we have a deeper understanding of why C++ switch statement is better than if statement, the specific use of the situation also needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!