Break statement in the default case | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Break statement in the default case

Still new to C++ and its unique syntaxes, I'm wondering if it makes any difference with or without the break statement switch (number) { case n: break; default: break; // or not }

2nd Oct 2021, 10:44 AM
Tim
Tim - avatar
6 Answers
+ 6
Slick Thank you for the explanation, have a good day!
2nd Oct 2021, 10:49 AM
Tim
Tim - avatar
+ 5
If the number parameter provided isn't one of the cases, default is called. If there's no default and no match you'll get unexpected output.
2nd Oct 2021, 10:46 AM
Slick
Slick - avatar
+ 5
Slick Is the break statement needed in the default case
2nd Oct 2021, 10:47 AM
Tim
Tim - avatar
+ 5
No, cause it's the final case and will break regardless. It just let's everybody know for sure.
2nd Oct 2021, 10:49 AM
Slick
Slick - avatar
+ 5
Adding to Slick, You'd still need the `break` IF the `default` case is placed in other slot but the last.
2nd Oct 2021, 10:57 AM
Ipang
0
switch (emotion){ case 1: System.out.println("You are happy!"); break; case 2: System.out.println("You are sad!"); break; case 3: System.out.println("You are angry"); break; case 4: System.out.println("You are surprised"); break; default: if (emotion > 4 || emotion <1 ){ System.out.println("Unknown emotion."); } } }
5th Nov 2022, 1:19 PM
Lalit Kumar