the_kshitij
the_kshitij

Reputation: 41

Use of case without switch, please explain the output of this code

We use cases with switch. But here the cases are inside the default case, so it should require one more switch. But the code doesn't give any compile time errors.

#include<iostream>
int main()
{
    int num=4;
    while (num)
    {
        switch(num)
        {

            default:
                case 1:
                    std::cout<<"Executing "<<num<<"\n";
                
                case 2:
                
                case 3:
    
                break;
        }
        num--;          
    }
    return 0;
}

Moreover the output is Executing 4 and then Executing 1. According to me the output should be Executing 1 because each time default is being entered. It will enter case 1 when value is 1. But first please explain how this is compiling, because according to me there should be a nested switch.

Upvotes: 2

Views: 163

Answers (2)

Raildex
Raildex

Reputation: 4817

case 1 to 3 are indented wrongly.

It's a so-called "fallthrough". If the switch hits the default case, it will fall through until it reaches a break meaning it will execute other cases on the way.
In your case, if it hits the default case, it will execute case 1, case 2 and case 3

Edit: I recommend ending each case with a break and putting default as the last case. Only if you really want to fallthrough and know what you do you could omit the break.

Upvotes: 1

Serge Ballesta
Serge Ballesta

Reputation: 149155

In a switch, all case and default are at the same level, you were just caught by the (stupid?) indentation, and a rather inconsistent use of default. In fact it should read:

    switch(num)
    {
            default:
            case 1:
                std::cout<<"Executing "<<num<<"\n";
            
            case 2:
            case 3:
                break;
    }

Meaning: do nothing (break) if 2 or 3, and display Executing ... for 1 or any other value.

This would do the same and would be IMHO more readable:

    switch(num)
    {
        case 2:
        case 3:
            break;

        default:
            std::cout<<"Executing "<<num<<"\n";
    }

Upvotes: 2

Related Questions