the switch statement

Status
Not open for further replies.
Code:
switch (yourMom.looks){
    case (isHot): 
        I.slap(yourMom.ass);
        break; // YOUR MOM
    case (isUgly): 
        I.slap(yourMom.face);
        break; // YOUR MOM
    default: I.FHUTA(yourMom);
}

if (yourMom.looks == isHot) {
    I.slap(yourMom.ass);
} else if (yourMom.looks == isUgly) {
    I.slap(yourMom.face);
} else {
    I.FHUTA(yourMom);
}
 
It's most useful when you use enums. Then you don't need to include a "default" statement, and the compiler will complain when the enumerated type grows but the switch statement doesn't.

If you had enum { Red, Green } and add "Blue", then

This should give a compilation error (although I'm not sure if it does on all compilers):
switch (foo)
{
case Red:
break;
case Blue:
break;
}

But this won't:

if (foo == Red)
else if (foo == Blue)
 
case $check in
"Y"|"Yes"|"y") break ;;

"N"|"n"|"No") continue ;;
*) echo "you entered an invalid choice!!"
continue ;;
esac

as opposed to

if [ "$check"="Y" ] || [ "$check"="y" ] || [ "$check"="Yes" ]
echo -n "hello"
elif [ "$check"="Y" ] || [ "$check"="y" ] || [ "$check"="Yes" ]
echo -n "this is a pain"
elif......
elif....
else

fi

saves a lot of bullshit code.
 
Large switch cascades are quicker to execute than branch statements, if you look at their structure in C/C++. Since cases in the switch can have only constant integer values (i.e. no ranges of values), the compiler can optimize the hell out of a switch statement. I also believe that switch statements can be supported at the hardware level (i.e. the assembly structure is very similar to the C/C++ syntax). Compilers can implement switches as table lookups or offsets, but branches have to be dealt with case by case.

The branch statement is faster than the switch statement if you're only dealing with one condition. This is because most modern CPU architectures support branch prediction, and a successful prediction does not waste any cycles. As you increase the number of cases, however, the benefits of branch prediction are only as good as the number of branch pipelines.

This is a generalization, BTW. If the language you're writing in supports ranges of values in the switch, the compiler may or may not optimize them well, or the switch may be syntactic (sp?) sugar for the branch statement.

EDIT: Just thought of a good analogy. Switches are like arrays, while branches are like linked lists.
 
Status
Not open for further replies.
Top Bottom