0

My code :-

#include <iostream>

using namespace std;

int main()
{
    int b=10;
    switch(b)
    {
    case 40:
        cout<<"no";
    default:
        cout<<"yes";
    case 10:
        cout<<"done";
    }
    return 0;
}

I was just experimenting with my code and tried this scenario. I had expected the output to be :-

yesdone

but the output was :-

done

According to me, since the compiler didn't know about the case 10: when it was reading the default: statement, it must also execute the stuff inside it.

My question :-

i) When is the default: case executed by the compiler and hence why is the output coming out to be

done

rather than

yesdone

Thanks for helping.

P.S :- I am using Code::Blocks with GCC compiler.

  • 1
    "According to what I know is that default case acts like the else in if-else selection statements. " no, it doesn't. The position of a `default` in a switch is not significant, any more than it is for any of the other cases. –  Feb 16 '18 at 20:30
  • " since the compiler didn't know about the `case 10:` " oh it definitely knows. – Hatted Rooster Feb 16 '18 at 20:33
  • I don't see how that's a duplicate. – Lightness Races in Orbit Feb 16 '18 at 20:33
  • It is not the case that the compiler reads your code only once and interprets everything on a single pass. From [cppref](http://en.cppreference.com/w/cpp/language/switch): "If condition evaluates to the value that is equal to the value of one of constant_expressions, then control is transferred to the statement that is labeled with that constant_expression." – 463035818_is_not_an_ai Feb 16 '18 at 20:33

1 Answers1

2

Your program jumps to the first matching case.

Only if none is found is the default jumped to instead.

[C++14: 6.4.2/5]: When the switch statement is executed, its condition is evaluated and compared with each case constant. If one of the case constants is equal to the value of the condition, control is passed to the statement following the matched case label. If no case constant matches the condition, and if there is a default label, control passes to the statement labeled by the default label. If no case matches and if there is no default then none of the statements in the switch is executed.

Whenever you find yourself thinking of switch as "a kind of if statement", immediately stop.

According to me, since the compiler didn't know about the case 10: when it was reading the default: statement, it must also execute the stuff inside it.

That is just not how C++ works; it is (somewhat) smarter than that.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055