Open In App

Fallthrough in C++

Last Updated : 13 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Fall through is a type of error that occurs in various programming languages like C, C++, Java, Dart …etc. It occurs in switch-case statements where when we forget to add a break statement and in that case flow of control jumps to the next line. Due to this when any case is matched with the specified value then control falls through to subsequent cases until a break statement is found. In C++, the error is not found on fallthrough but in languages like Dart, an error occurs whenever a fallthrough occurs.

It is not always necessary to avoid fallthrough, but it can be used as an advantage as well.

Program 1:

Below is the program to illustrate how fall-through occurs:

C++




// C++ program to illustrate
// Fallthrough in C++
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    int n = 2;
  
    // Switch Cases
    switch (n) {
    case 1: {
        cout << "this is one \n";
    }
    case 2: {
        cout << "this is two \n";
    }
    case 3: {
        cout << "this is three \n";
    }
    default: {
        cout << "this is default \n";
    }
    }
  
    return 0;
}


Output:

this is two 
this is three 
this is default

Explanation: In the above code, there is no break statement so after matching with the 2nd case the control will fall through and the subsequent statements will also get printed.

How to Avoid Fall Through?

To avoid Fall through, the idea is to use a break statement after each and every case so that after matching it goes out of the switch statement and control goes to the statement next to the switch statement.

Program 2:

Below is the program to illustrate how to avoid the fall through:

C++




// C++ program to illustrate how to
// avoid fall through
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    int n = 2;
  
    // Switch Cases
    switch (n) {
    case 1: {
        cout << "this is one \n";
        break;
    }
  
    case 2: {
        cout << "this is two \n";
  
        // After this break statement
        // the control goes out of
        // the switch statement
        break;
    }
    case 3: {
        cout << "this is three \n";
        break;
    }
    default: {
        cout << "this is default \n";
        break;
    }
    }
  
    return 0;
}


Output:

this is two


Like Article
Suggest improvement
Share your thoughts in the comments