switch
statement
The switch statement is used to select one of many code blocks to be executed. Very similar to if-else statements.
I don’t use these much.
Example
int a = 5;
switch(a) {
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
default:
...
break;
}
What is the
default
keyword?The
default
keyword specifies some code to run if there is no case match
BE CAREFUL, if you forget the break
, then the statement will continue running.
For example,
switch (1) {
case 1:
std::cout << '1'; // prints "1",
case 2:
std::cout << '2'; // then prints "2"
}
When should you use
switch
overif ... else
?If a switch contains more than five items, it’s implemented using a lookup table or a hash list.
Therefore, if you are comparing against constant values, the
switch
syntax is likely preferable, since you can compare in time rather than in time for anif...else
statement.