Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Switch cases should <em>almost</em> always have a <code>default</code> case.</p> <p><strong>Reasons to use a <code>default</code></strong></p> <p><em>1.To 'catch' an unexpected value</em></p> <pre><code>switch(type) { case 1: //something case 2: //something else default: // unknown type! based on the language, // there should probably be some error-handling // here, maybe an exception } </code></pre> <p><em>2. To handle 'default' actions, where the cases are for special behavior.</em></p> <p>You see this a LOT in menu-driven programs and bash shell scripts. You might also see this when a variable is declared outside the switch-case but not initialized, and each case initializes it to something different. Here the default needs to initialize it too so that down the line code that accesses the variable doesn't raise an error.</p> <p><em>3. To show someone reading your code that you've covered that case.</em></p> <pre><code>variable = (variable == "value") ? 1 : 2; switch(variable) { case 1: // something case 2: // something else default: // will NOT execute because of the line preceding the switch. } </code></pre> <p>This was an over-simplified example, but the point is that someone reading the code shouldn't wonder why <code>variable</code> cannot be something other than 1 or 2.</p> <hr> <p>The only case I can think of to NOT use <code>default</code> is <em>when the switch is checking something where its rather obvious every other alternative can be happily ignored</em></p> <pre><code>switch(keystroke) { case 'w': // move up case 'a': // move left case 's': // move down case 'd': // move right // no default really required here } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload