c++ – Switch statement, is break needed after default label?

Question:

What's the point of having a break statement after the label default if the switch after default ends anyway?

I often see examples, both with and without break after default :

switch(number)
{
  case 0: cout << "Too small.\n";  break;
  case 1: cout << "One.\n";  break;
  case 2: cout << "Two.\n"; break;       
  case 3: cout << "Three.\n"; break;
  default: cout << "Too large.\n"; 
  break; // какой смысл в этом break?
}

Answer:

Syntactically, there is no need for the very last break , no matter what section it is in.

switch(number)
{
  case 1: cout << 1; break;
  case 2: cout << 2; break;       
  default:
  case 0: cout << "Мало"; break;
  case 3: cout << "Много"; /*break;*/
}

Essentially, break is a goto to the position immediately after the curly brace. ( And continue to the position before it, but only in loops )
In this light, the redundancy of this operator is obvious.


However, this break can still be useful if the list of cases ( case ) might change in the future.
In the presence of all break , it is more difficult to make a mistake and get this error:

switch(number)
{
  case 1: cout << 1; break;
  case 2: cout << 2; break;       
  default:
  case 0: cout << "Мало"; break;
  case 3: cout << 3;         // При добавлении строчки, забыли добавить пропущенный break
  case 4: cout << "Много";
}

This becomes more relevant if the sections are not so trivial, and just looking around the switch is not immediately clear what belongs to what.

Scroll to Top