C++ Fall through,

I tried to learn about C++ fall through inside switch case, several cases can be considered for below code.

#include <iostream>
using namespace std;

int main() {
    
    int n = 2;
    //Switch case
    
    switch(n) {
        case 1: 
            cout <<"this is one \n";
            //break;
        
        case 2:
            [[fallthrough]];
            //cout <<"this is two\n";
            //break;
        
        case 3:
            cout <<"this is three\n";
            
        
        default: 
            cout<< "this is default \n";
            break;
    }
    return 0;
}

Output:

this is three
this is default 

Ref:
https://www.geeksforgeeks.org/fallthrough-in-c/
https://en.cppreference.com/w/cpp/language/attributes/fallthrough

#include <iostream>
using namespace std;

void g(), h(), i();
int n=2;
int main() {
    switch (n)
    {
        case 1:
        case 2:
            g();
            [[fallthrough]];
        case 3:
            h();
        case 4:
            if (n<3) {
                i();
                [[fallthrough]];
            }
            else {
                return 1;
            }
        case 5:
            while (false) {
                [[fallthrough]];
            }
        case 6:
            [[fallthrough]];
        default:
            return 0;
        
    }
    
   return 0;
}

Another good example:

/******************************************************************************

                              Online C++ Compiler.
               Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/
#include <iostream>
using namespace std;

int f(int n) {
    switch (n) {
        case 1:
        case 2:
            n=n+20;
            [[fallthrough]];
        case 3:
            n=n+30;
        case 4:
            [[fallthrough]];
        case 5:
            cout << "heyy!" << endl;
            
    }
    return n;
}

int main() {
    cout << f(1) <<endl;
    cout << f(2) <<endl;
    cout << f(3) <<endl;
    return 0;
    
}

Ref: https://stackoverflow.com/questions/51983560/should-there-be-a-diagnostic-from-gcc-compiler-for-this-ill-formed-c-code-invo

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *