int i = 10;
switch( i )
{
case 1:
// do sth1
break;
case 2:
// do sth2
break;
case 3:
// do sth3
break;
default:
// do sth default
break;
}
Question 1> When the switch statement executes, do we jump directly to the right case statement or do we search from top to bottom?
Answer: Directly jump to the right case statement.
Question 2> Should we use a break statement after the default statement?
Answer: Depends. If the default statement is the last case statement, then using break is NOT necessary.
Did I get the answers right in the above questions?
Question 1: Depends on the compiler. C++ standard does not require that a jump table be set up.
In many cases, especially with small number of sparse cases, GCC, MSVC and other compilers will do clause-by-clause check (as if it were an if statement). To give an example, suppose your cases were 1, 15, and 1000000. It would not be efficient code-wise to do a direct jump.
gcc has the option
-fno-jump-tablesto force it to build the equivalent if-else list.Question 2: The break statement is not required for the last clause. It should be omitted if execution should flow down.