[Switch] the difference between switch and if
If it is purely a number or character, we recommend that you use switch, because it will only retrieve the variable value once in the start switch brackets, and then compare this value with the case set below, however, if you use the if clause, You must retrieve the variable value every time you encounter a conditional clause. The difference in efficiency is here. For example:
If (A = 1)
//...
Else if (a = 2)
//...
Else if (a = 3)
//...
In the worst case, when a = 3, this program fragment requires three comparisons, and the value of variable A must be retrieved once for each comparison. Switch:
Switch ()
{
Case 1:
//...
Break;
Case 2:
//...
Break;
Case 3:
//...
Break;
}
In this program fragment, only the value of variable A is taken out in the brackets of the switch at the beginning, and then the following case is compared one by one. The difference in efficiency is here. Of course, it is not good to use if. In case of composite conditions, the switch cannot help, because it cannot combine complex conditional statements in the switch, then you have to use if. Simply put, if and switch can be used flexibly together.
Top me