To all those who use C++ and to the creator of C++ . I want to ask a question . What is the use of the default case in a switch statement ?
It is actually to be executed when no case is satisfied , but it is executed even when there is no break; after the last case and the last case is satisfied. Why is it so ?
for eg.,


  case 1 : cout<<"ONE"; break;
  case 2 : cout<<"TWO"; 
  default :cout<<"NONE";

In this case , if the input is 2 , it should output only TWO , but it will OUTPUT TWO NONE according to the C++ compiler. This is wrong with respect to the purpose of the default statement .

Recommended Answers

All 21 Replies

if i = 2, put an extra break after the ; on line 4 of your code.
You will notice there is nothing wrong with the C++ compiler.
Happy computing.

That's fine i know those basics. The default should not be executed without a break too. According to the purpose of the default statement , it should be executed only when no case is true , then why should it be executed when the last case is true , but does not have a break; ?

If every case has a break no default will be executed if the switch condition matches a case.

But it should not be executed even without a break; as its purpose says that it should be executed only when no case matches.

If a matching expression is found, control is not impeded by subsequent case or default labels. The break statement is used to stop execution and transfer control to the statement after the switch statement. Without a break statement, every statement from the matched case label to the end of the switch, including the default, is executed.

You can read the whole story here

A fault in C++ !

i'm not in a position to say such.

it should be executed only when no case is true

100% agree with you.

If every case has a break no default will be executed if the switch condition matches a case.

yes , correct. but this is not what the op wants. i think he wants the explanation about "why break statement becomes essential in switch statement ?"

i can't answer the question of why ?but still i say that it is due to flow of control .

This may be fault in c++ because has improved this(i'm learning it).

You didnt get my point . I know all tose stuff , i was asking about another issue.

He guys, it is what it is. In C#(my favorite btw) you even have to put a break after the default statement to make a switch/case work.

Ok, first off:

switch (i) {
case 1:               // If i = 1
    cout << "ONE";    // Print "ONE"
    break;            // Stop here, and leave the switch.

case 2:               // If i = 2
    cout << "TWO";    // Print "TWO"
    break;            // Stop here, leave the switch.
                      // - Ommiting this will run the default case.

default:              // If i = anything else
    cout << "NONE";   // Print "NONE"

If you're in a switch-case and C++ sees a break it will leave the switch. But, if it does not see a break, then it will continue to the next case. This is a feature that allows you to do some nice conditional cascading. That is the purpose.

The default case is ONLY executed if all of the other ones fail AND the switch is broken at some point before. Don't forget them unless you want a cascading effect.

Your code neglects to break before the default, so it is also executed. Thus, your compiler give the correct ouput of "TWONONE".

But it should not be executed even without a break; as its purpose says that it should be executed only when no case matches.

Your source is incorrect, not C++. C++ defines it to work the same way we are telling you. You need to use breaks; otherwise, it IS DEFINED to carry onto the next case (for very nice reasons).

commented: Very well explained! +15

Learner010 has got my point. Whom should i ask about it ?

Learner010 has got my point. Whom should i ask about it ?

We've already explained to you why breaks are important.

Unless your taking about the "fault" with C++. This is not a fault with C++. If the feature you suggested was implemented it would break backwards compatibility, as well as make cascading switches a lot more difficult. It would be a headack for everyone, and make C++ a worse language. The people who are currently developing C++ standards, know what they're doing very very well. What I can tell you is trust them. The've been at this for far longer then you have.

If you wanted to "try to fix" the "fault", you would need to join the JTC1/SC22/WG21 C++ Standards Committee, and ask them about it. I can tell you now though, it will not be accepted.

I agree with Hiroshe. In C# you even have to write a break statement AFTER a default! I found this very strange in the beginning, but I guess the C# development team has a very good reason to do it that way.
Consider it a rule. Like it is a very good rule if a country has the rule Let's drive on the right side of the road. If in your country the rule is the left side, then you better hold to the rule if you're in the other country. :)

Ok ... forget about everything. Think this way. There is no break; after the last case , and the last case is satisfied . Now , since the default is only and only executed when no case matches , it should not be executed. But it is executed. Why ???

Because a switch case statement "falls through" all the cases and ALSO the default if you don't use break or return statements. B.T.W. the default clause is optional.

Here is where the logic is wrong:

"since the default is only and only executed when no case matches"

That's not true. If no other case matches, then the switch will jump to the default case. It's an "if-then" rule, not a "if-and-only-if" rule. The fact that no other case matches is sufficient to get the default case executed (jumped to), but it is not necessary. In other words, it's a one-way rule:

  • "If no case matched, then execute default": true
  • "If execute default, then no case matched": false

So, with that faulty logic statement removed, your problems vanish.

So, to your question, "Why???", well, the reason is that if you understand the rule correctly, the compiler does exactly what it is required to do.

By the way, this is not a problem with C++, but rather with C (or one of its earlier predecessor). I would expect that all programming languages derived from C (which are essentially all mainstream programming languages used today) have the exact same behavior for switch-statements. So, that's another answer to the infamous "Why???" question: it's just traditionally always been so, since the dawn of programming (i.e., when Ritchie / Thompson created C). AFAIK, only languages derived from Pascal (which are nearly extinct now) have the behavior that you are describing.

Furthermore, there is a technical reason "Why???" the switch statement has this behavior. Basically, a switch statement is a series of GOTO statements with case-labels. GOTOs and labels are the most primitive forms of conditionals (or "jumps"). They are no longer really used, thank goodness for that, but the switch-statement is its closest relative. In other words, the switch-statement says "goto whichever case matches or the default one, and start executing from there". The different cases should not be seen as different sections of code, but rather as different starting points. This simplicity in the way switches work is something that used to matter, and still does to some.

And finally, as Hiroshe pointed out, there are nifty tricks that do rely on the cascading conditionals. I have used it from time to time. It can be a very handy feature. The most classic trick that relies on this feature is Duff's device.

commented: Right! +12
commented: Deep knowledge! +15

I am not asking about the rules of c++ . Its a different issue.

I wasn't born yesterday, and I recognize that little game you're playing by constantly diverting and deflecting, trying to trigger more responses and frustrations. I believe the colloquial name for that is "trolling". The answers to your questions and concerns have been pretty clear and comprehensive at this point. I see no reason to continue elaborating, and unless you provide more substantive explanations of your (mis)understandings, I would advise others not to waste any more time on this guessing game either.

If you are truly genuine about your misunderstanding of this situation, you are doing a poor job at communicating that. I advise you to provide a clear and comprehensive explanation of your concern or question. Nobody wants to keep guessing what you mean or want to know, without you clearly expressing it.

I've cleared myself to the extreme limit I could ... And I find no reason now to communictae my explanation to you . Thank you for wasting your time at my question MIKE :/

commented: We don't like rude people here! -3

if entered inputs are wroung.. for example if all the inputs u entered is not soutable or valid according to the given cases, ( u provided in the cases ) then it's compulsry that default condition execute..

The reason is that the language is simpler to understand if every case clause has fall-through behavior. If default: sections didn't have full-through behavior (on entry), that would be surprising to people because that's different behavior than what you get with all the other clauses.

Also, if such was the behavior of C++, code that relied on that behavior would be fragile. Adding a new enumeration value and a new case clause just before the default: case would require the programmer to remember to insert a break; statement at the end of the previous case clause.

That would lead to lots of bugs.

First rule of programming: when in doubt about whether something is a bug in the compiler/language spec or a bug in your code, assume it's a bug in your code.
Second rule of programming: when in doubt whether something is a problem with the language spec or your understanding of said spec, assume it's a problem with your understanding.
Third rule of programming: don't try to invent new languages or libraries if there's existing ones that can be bludgeoned or cajoled into doing the job you need done.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.