Default as First Option in Switch Statement

default as first option in switch statement?

It is an unusual idiom, it causes a little pause when you're reading it, a moment of "huh?". It works, but most people would probably expect to find the default case at the end:

switch($kind)
{
case 'kind2':
// do some stuff for kind2 here
break;

// [...]

case 'kindn':
// do some stuff for kindn here
break;

case 'kind1':
default:
// Assume kind1
$kind = 'kind1';

break;

}

Javascript switch statement - default first OK?

I've never seen someone use this approach before. It's clever. As a side note, clever is a two-edged blade; if this is code that anyone other than you will be touching, I strongly suggest a comment there to make it clear you did that on purpose or someone is going to alter it (because it 'looks wrong') and break it without realizing the intent.

The documentation indicates that default is not required to be the last clause.

If you find a browser were it does NOT work, you could modify it slightly thus and avoid the default:

function testSwitch(definition) {
var term, minLength, boundaryStart, boundaryEnd;
switch (definition.length > 4 ? 5 : definition.length) {
case 5:
case 4:
boundaryEnd = definition[3];
case 3:
boundaryStart = definition[2];
case 2:
minLength = definition[1];
case 1:
term = definition[0];
break;
case 0:
console.log('fail')
return;
}
console.log(term, minLength, boundaryStart, boundaryEnd);
}

Switch statement: must default be the last case?

The C99 standard is not explicit about this, but taking all facts together, it is perfectly valid.

A case and default label are equivalent to a goto label. See 6.8.1 Labeled statements. Especially interesting is 6.8.1.4, which enables the already mentioned Duff's Device:

Any statement may be preceded by a
prefix that declares an identifier as
a label name. Labels in themselves do
not alter the flow of control, which
continues unimpeded across them.

Edit: The code within a switch is nothing special; it is a normal block of code as in an if-statement, with additional jump labels. This explains the fall-through behaviour and why break is necessary.

6.8.4.2.7 even gives an example:

switch (expr) 
{
int i = 4;
f(i);
case 0:
i=17;
/*falls through into default code */
default:
printf("%d\n", i);
}

In the artificial program fragment the
object whose identifier is i exists
with automatic storage duration
(within the block) but is never
initialized, and thus if the
controlling expression has a nonzero
value, the call to the printf function
will access an indeterminate value.
Similarly, the call to the function f
cannot be reached.

The case constants must be unique within a switch statement:

6.8.4.2.3 The expression of each case label shall be an integer constant
expression and no two of the case
constant expressions in the same
switch statement shall have the same
value after conversion. There may be
at most one default label in a switch
statement.

All cases are evaluated, then it jumps to the default label, if given:

6.8.4.2.5 The integer promotions are performed on the controlling
expression. The constant expression in
each case label is converted to the
promoted type of the controlling
expression. If a converted value
matches that of the promoted
controlling expression, control jumps
to the statement following the matched
case label. Otherwise, if there is a
default label, control jumps to the
labeled statement. If no converted
case constant expression matches and
there is no default label, no part of
the switch body is executed.

Should switch statements always contain a default clause?

Switch cases should almost always have a default case.

Reasons to use a default

1.To 'catch' an unexpected value

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
}

2. To handle 'default' actions, where the cases are for special behavior.

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.

3. To show someone reading your code that you've covered that case.

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.
}

This was an over-simplified example, but the point is that someone reading the code shouldn't wonder why variable cannot be something other than 1 or 2.


The only case I can think of to NOT use default is when the switch is checking something where its rather obvious every other alternative can be happily ignored

switch(keystroke)
{
case 'w':
// move up
case 'a':
// move left
case 's':
// move down
case 'd':
// move right
// no default really required here
}

Should we break the default case in switch statement?

Should we use a break; in the last default case?

From The C programming language - Second edition (K&R 2):

Chapter 3.4 Switch

As a matter of good form, put a break after the last case (the default
here) even though it's logically unnecessary. Some day when another
case gets added at the end, this bit of defensive programming will
save you.

Why my switch case always goes to default case?

You're reading an int, but your switch is comparing the first digit of that int to various characters. Now, char is a numeric type, so this (kind of) works, but the value of '0' does not equal 0 and so on for all digit characters.

Thus you go straight to the default case.

More correctly:

switch (a) {
case 0:
printf("black ");
break;

// etc.
}

You could also simply have an array of strings and use the digit to index it. Making sure of course to validate that a is a valid index.

char *colors[] = { 
"black", "brown", "red", "orange", "yellow",
"green", "blue", "violet", "grey", "white"
};

if (a >= 0 && a <= 9) {
printf("%s ", colors[a]);
}
else {
printf("unknown value ");
}

Default clause before case sections in the switch statement

The order of case labels within a switch block in the code has nothing to do with which one is executed. The default label is executed if no case matches or it falls through from a case above it. Having it first in the code base doesn't change this.

The one advantage to having default be first is that it's impossible for a case above it to accidentally or intentionally fall through to default. This means default will run if, and only if, the value matches no case statements in the switch block.

To be extremely pedantic you could still hit the default label with an explicit goto. That is pretty rare though.

why does this simple switch statement always run the default

switch compares what you switch with against the cases. So, if you have case x < 0.5: which you want to run, that case will run if the expression you switched against was true:

var x = 0.6;
switch (true) { case x < 0.5: console.log("less"); break; case x > 0.5: console.log("more"); break;
default: console.log("its the dflt");};
console.log(x);


Related Topics



Leave a reply



Submit