Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using "default" case in a switch statement a good habit? [closed]


when I'm using a switch(in Java in this case) I normally use the default case if needed. One of my teachers told me that when he used to program in Pascal, that case didn't exist. He said that if it didn't exist in Pascal it shouldn't be something good to use.

My questions are:

  • Is it wrong to use the default case?
  • How does it work internally?

Thanks in advance.

like image 289
Daniel Higueras Avatar asked Mar 06 '11 15:03

Daniel Higueras


People also ask

Is a default case necessary in a switch statement?

If no default clause is found, the program continues execution at the statement following the end of switch . By convention, the default clause is the last clause, but it does not need to be so. A switch statement may only have one default clause; multiple default clauses will result in a SyntaxError .

Should default be last in switch case?

A 'switch' statement should have 'default' as the last label. Adding a 'default' label at the end of every 'switch' statement makes the code clearer and guarantees that any possible case where none of the labels matches the value of the control variable will be handled.

What is true for the default case in the switch statement?

A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

What is the use of default in switch control statement?

2) Default: This keyword is used to specify the set of statements to execute if there is no case match. Note: Sometimes when default is not placed at the end of switch case program, we should use break statement with the default case. 2) Duplicate case values are not allowed. 3) The default statement is optional.


1 Answers

I would consider it a bad habit not to use it.

  • If you think the default case will never happen, throw an exception to be sure
    • If you switch over an enum, it may happen that someone added another value
    • If you switch over an integer, it is always possible that an unexpected value is found
  • because the default case always happens when you expect it the least
  • As far as I know there is something similar in Pascal

Edit:

This is Pascal, just to prove your teacher wrong

case place of
  1: writeln('Champion');
  2: writeln('First runner-up');
  3: writeln('Second runner-up'); 
  else writeln('Work hard next time!'); 
end;
like image 89
Cephalopod Avatar answered Sep 17 '22 03:09

Cephalopod