Reputation: 35984
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?
Upvotes: 1
Views: 569
Reputation: 69958
Question 1> When the switch statement executes, do we jump directly to the right case statement or do we search from top to bottom?
I don't think there is any mention about this implementation detail in the standard. However, your answer is correct for that.
Question 2> Should we use a break statement after the default statement?
Yes, it depends on the requirement. Sometime you may not need it at all. Consider the situation, where you want to do something for default:
case and little lesser thing for say case 1:
. For example,
switch(i)
{
default: foo();
case 1: bar();
break;
case 2: abc();
break;
case 3: xyz();
break;
}
Upvotes: 0
Reputation: 75130
You are correct for answer two, except I would add that a break is necessary after the default statement if it's the last case or its not and you don't want it to fall through. But that's just a nitpick.
The answer to question one depends on if optimisations are enabled and how smart your compiler is. If optimisations are low or disabled (or your compiler is just old and/or not very sophisticated) it will do a search from top to bottom skipping over the default case (thanks q0987). If optimisations are enabled and the compiler decides to do it, it will be optimised into a jump table, in which case it will jump directly to the correct case.
Upvotes: 1
Reputation: 26251
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-tables
to 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.
Upvotes: 4