+ 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 }
7 Antworten
+ 6
Slick
Thank you for the explanation, have a good day!
+ 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.
+ 5
Slick
Is the break statement needed in the default case
+ 5
No, cause it's the final case and will break regardless. It just let's everybody know for sure.
+ 5
Adding to Slick,
You'd still need the `break` IF the `default` case is placed in other slot but the last.
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.");
}
}
}