According to this book I am reading:
Q What happens if I omit a break in a switch-case statement?
A The break statement enables program execution to exit the switch construct. Without it, execution continues evaluating the following case statements.
Suppose if I have codes looking like
switch (option}{ case 1: do A; case 2: do B; default: do C; break; }
Does this mean if I choose case 1, the A and C are done. If I choose case 2, B and C are done. If i choose neither, then only C is done.
if so, what happens if we omit the break after do C.
I assume these are bad programming practice, but I am curious what would happen to get a deeper understanding how it all works. Thanks
Break will return control out of switch case.so if we don't use it then next case statements will be executed until break appears. The break statement will stop the process inside the switch.
Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached. This continuation may be desirable in some situations. The default statement is executed if no case constant-expression value is equal to the value of expression .
Yes, you can use return instead of break ... break is optional and is used to prevent "falling" through all the other case statements. So return can be used in a similar fashion, as return ends the function execution.
Can the last case of a switch statement skip including the break? Even though the last case of a switch statement does not require a break statement at the end, you should add break statements to all cases of the switch statement, including the last case.
You execute everything starting from the selected case up until you see a break
or the switch
statement ends. So it might be that only C is executed, or B and then C, or A and B and C, but never A and C
If you don't include break in any of case then all the case below will be executed and until it sees break.
And if you don't include break in default then it will cause no effect as there are not any case below this 'Default' case.
And not using break generally considered as a bad practice but some time it may also come handy because of its fall-through nature.For example:
case optionA:
//optionA needs to do its own thing, and also B's thing. //Fall-through to optionB afterwards. //Its behaviour is a superset of B's.
case optionB:
// optionB needs to do its own thing // Its behaviour is a subset of A's. break;
case optionC:
// optionC is quite independent so it does its own thing. break;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With