Control Structures 2: Switch

Submitted by M E Senturk on Wed, 09/16/2009 - 22:53

In this part, we will go on "control structures" with switch. Sometimes using nested ifs seems boring. Beside this fact, flow of the program does not let you to use a simple nested if structure. When this happens, you need to declare conditions clearly and let the program flow due to these declarations. We use switch condition for the situations like this. Let's see how can we use switch statement:

..
int conditional_variable;
scanf("%d",&conditional_variable);
switch('conditional_variable')
{
    case 0:
        printf("Conditional Variable is 0, some special functions will run due to this value");
        //do something
        break;
    case 1:
        printf("Conditional Variable is 1, some special functions will run due to this value");
        //do something else;
        break;
    ....
    default("You entered a meaningless value for Conditional Variable.");
        break;
}

By inspection, we can observe that switch element includes case elements and a default element.

the variable in parenthesis of switch element as we name it conditional_variable, the variable that controls the flow. For various values of this variable, various cases and various functions run with various parameters. As you see, in our example, if the conditional_variable is 0 then prints some text. If the conditional_variable is 1 then prints another text(different than the first one).

"default" case is the case to go if the value of conditional variable does not match any of the case values.

Conditional variable does not have to be an integer. It can be any type. But using floats and doubles is not sensible, due to the precision of value assignments(I saw too much 1.0!=0.99999).So i advise you to use integers or chars or pointers(we will see them later) of them.

There are "break" elements at the end of each case. This takes you out of the switch statement. You should use it. If you don't then your program will run from the specified case to downward, running all other cases you write after.

 

Let's write a code for a simple menu for a console application using switch.

#include <stdio.h>
int main()
{
    int choice;
    prinf("Enter your choice using menu number:\n1. Say Hi\n2. Say Hello\n3. Say How are you\n0. Exit\nChoice: ");
    scanf("%d",&choice);
    switch(choice)
    {
        case 1:
            printf("Hi!");
            break;
        case 2:
            printf("Hello!");
            break;
        case 3:
          printf("How are you?");
          break;

case 0:

          printf("Now you are going.");
          break;
      default:
          printf("A meaningless entry");
          break;
    }
    return 0;
}