Skip to main content

switch statements:

A switch is a way to do multiple selection pathways on matching of a values. Note that any sort of complex boolean operations are not supported. Thus, checks that involve other operators such as >, <, >=, <= are not allowed in switch check. Switch only supports matching expressions.

For example, here is an example where we might want to use an if/else if/.../else type of block. The switch statement is a more convenient way to do the same checks.

Determining Face Value of a card based on numeric rank

In a deck of playing cards many of the values are numeric 2, 3, ...10, but there 4 that are not numeric, A (1), J(11), Q(12), K(13) (ace, jacks queens, kings). Given the numeric rank representation of a card print out the associated value of the card (2-10, A, J, Q, K)



void printFace(int numeric){

if(numeric == 1){
printf("A\n");
}
else if(numeric == 11){
printf("J\n")
}
...

}

Using a switch() statement we can check the numeric value and every time there is a match, we perform the statement for that case

void printFace(int numeric){

//we are checking the valu in the variable called numeric
switch(numeric){
//if it matches with 1 we do all steps until the break; or end of the switch block
case 1:
printf("A\n");
break;
case 11:
printf("J\n");
break;
case 12:
printf("Q\n");
break;
case 13:
printf("K\n");
break;
default:
printf("%d", numeric);
};
}

You will notice the use of break; in the switch block. The break; is needed because of how switches work in C. If a value matches it will start executing all code from that point on until either the end of the switch is reached or until a break is encountered.

The switch statement can be a useful construct for doing matched base selection but it must be used with care.