DEV Community

Cover image for Code Smell 221 - Missing Break in Switch
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Code Smell 221 - Missing Break in Switch

You abuse cases in switches and make subtle mistakes

TL;DR: Cases are GOTOs, but you might be missing them

Problems

Solutions

  1. Add the missing break

  2. Convert the switch into a polymorphic hierarchy

  3. Remove the default switch

Context

In a switch statement, when a match is found in a particular case, the code execution will start from that case and continue executing all subsequent cases until a break statement is encountered or the switch block ends.

This behavior is called "fall-through."

Forgetting a break clause will continue with the following case.

This is similar to a very serious vulnerability that implied an urgent release.

Sample Code

Wrong

  switch (number) {
      case 1:
          printf("Number is 1.\n");
          break;
      case 2:
          printf("Number is 2.\n"); 
          // Missing break
      case 3:
          // Case 2 will continue here
          printf("Number is 3.\n"); 
          break;
      default:
          printf("Number is not 1, 2, or 3.\n");
  }

// If the number is 2 this will output numbers 2 and 3
Enter fullscreen mode Exit fullscreen mode

Right

  switch (number) {
      case 1:
          printf("Number is 1.\n");
          break;
      case 2:
          printf("Number is 2.\n"); 
          break; // Added 'break' to prevent fall-through
      case 3:
          printf("Number is 3.\n"); 
          break;
      default:
          printf("Number is not 1, 2, or 3.\n");
  }

// This is correct even though switches AND defaults
// Are other code smells
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

Many linters and also ChatGPT detect this smell.

Tags

  • IFs

Conclusion

Using switches and causes is problematic, your need to use higher-level sentences.

Relations

More Info

Sonar Source

Common Weakness Enumeration

Apple's Security Defect

Disclaimer

Code Smells are my opinion.

Credits

Photo by Nikola Johnny Mirkovic on Unsplash


I am not terribly dogmatical about the goto statement. I have the uncomfortable feeling that others are making a religion out of it, as if the conceptual problems of programming could be solved by a single trick, by a simple form of coding discipline!

Edsger Dijkstra


This article is part of the CodeSmell Series.

Top comments (0)