The IF else statement is the most commonly used method for determining branch conditions. However, it is more intuitive and convenient to use switch when there are too many branch conditions. Here are two simple examples.
C ++:
Int num = 2;
Switch (Num)
{
Case 1: cout <"one"; break;
Case 2: cout <"two"; break;
Case 3: cout <"three"; break; // break can be omitted
Default: cout <"default"; break; // default is not required and can be omitted
}
C #:
Int num = 2;
Switch (Num)
{
Case 1: console. writeline ("one"); break;
Case 2: console. writeline ("two"); break;
Case 3: console. writeline ("three"); break; // The break cannot be omitted.
Default: console. writeline ("default"); break; // default can be omitted.
}
The usage of swith in C ++ and C # is almost identical. Only a few small differences exist. C # has made some improvements based on C ++.
Differences:
1.The variable type in switch () brackets in C ++ can only be an integer or can be converted to an integer by default. for example, Int, long, bool, Char, enum. (Of course, the expression also works, as long as the result meets the preceding conditions ). but float, double, and string won't work. in addition, the custom type, such as a class, can be converted to int by default if there is Operator overload in the class. that's fine. however, in most cases, the custom type is rarely used in the switch.
The variable types in switch () brackets in C # Can Be byte, short, Int, long, bool, and enum.There is also a string, which cannot be used in C ++.Like C ++, expressions can be used, but float and double cannot. A user-defined type can also be converted.
2.Break in C ++ can be omitted. however, this can easily cause a problem. if there is no break, when the execution of a branch meets the condition, the branch following it will be executed. in the above example, if all break is removed. the result is twothreedefault.
C # requires you to use break forcibly. If you do not need it, an error will be reported during compilation. In this way, errors caused by forgetting to Write Break in C ++ will not be committed.
Supplement: You can also use return to replace break. However, return indicates that the entire function is exited, while break only exits the switch statement block.
If the logic in the switch statement block is complex, you can also use the GOTO statement.
For example
Int num = 2;
Bool check = false;
Switch (Num)
{
Case 1: console. writeline ("one"); break;
Case 2: console. writeline ("two"); goto label;
Case 3: console. writeline ("three"); break;
}
Of course, many people have said that when writing code, try to use the GOTO statement as much as possible.