~ Introduction to Programming: C ~

Session 9 - Switch..Case and Constants

<<  Back to Contents Page

Session 9 - Switch..Case and Constants 

In This Session...

In this session we will be covering the following topics:-

Review of Last Session

Last session we covered:-

The switch..case statement

There are many instances when creating C programs where we wish to perform an action, or set of actions, according to a selected option. A simple example that we looked at last session was the selection of either the 'Y' or 'N' key to decide whether to quit a program, or choosing an option between 1-4 (or 0 to quit) in the calculator example.

It is often useful to be able to look at the contents of a variable, and take one of a number of courses of action according to its contents.

For this, we may use the switch...case command, which look a little peculiar at first glance, but can make your programs easier-to-follow.

For example:-



char ch;

ch=toupper(getch());

switch (ch) {

    'A': printf("You pressed A");

          break;

    'B': printf("You pressed B");

          break;

    'C': printf("You pressed C");

          break;

    default: printf("You did not press A, B, or C");

}

 

In this example, the user presses a key, and the results are placed in a variable called ch.

After the switch keyword, appears the variable in which we are to look. This appears in brackets. In this case, we are looking at the ch variable to see what key the user pressed on the keyboard.

All of the different options are grouped together between an opening and closing curly brace, which start and end the switch command.

Each of the 'case' commands inside these curly braces is an 'entry point' giving a constant value to compare to the ch variable - e.g. case('A'): means that if the ch variable contains the character 'A' then the instructions that follow the colon (:) will be executed (i.e. done!) .

There is a final option you can choose called default: which gives the place to start executing instructions if none of the other cases compare with the variable - similar to the else statement used with the if statement.

The switch statement is similar to a number of if statements, distinguished with else statements.  However, with an if statement, you would need to keep re-stating the variable you wish to check - e.g.

 
if (ch=='A') printf("You pressed A");

else if (ch=='B') printf("You pressed B");

else if (ch=='C') printf("You pressed C");

else printf("You did not press A, B, or C");   

 

Notice that when using the switch..case command, the exit-point for each 'case' is given by the break command. Like the use of break in a while loop, this will jump to the instruction following the closing } curly brace of the switch command. If you do not include the break command, execution continues to the instructions following the next case command, until the next break command is reached, or until the closing } of the switch command is reached.

Take the following example:-

 
char ch;

ch=getch();

switch (ch) {

    case('1'): printf("You pressed 1");

    case('2'):

    case('3'): printf("You pressed 1 or 2 or 3");

               break;

    case('4'): printf("You pressed 4");

      default: printf("You did not press 1, 2 or 3");

}

 This example is similar to the previous example.  This switch() looks a little different in that execution does not always stop at the next case - it carries on until a break command is found, which stops execution of the commands in the switch() and continues execution after the closing curly bracket.

The result is that if the user presses 1, a message saying this is displayed, and excution continues inside the switch command. If the user presses 2 then no action is taken, but execution continues. If 3 is pressed, then a message is displayed saying 1, 2, or 3 has been pressed - at this point, because the '1' and '2' cases did not have a break command, they can all display this line.  There is then a break command, which means that the next line to be executed will be the line after the closing curly brace } of the switch command. If 4 is pressed, then a message saying this is displayed.

Finally, if anything else is displayed, then a message is displayed saying that anything other than 1-3 was chosen. If 4 was pressed, this would also be displayed, as no break command follows the case statement for '4'.

Exercise 32 - Switch..Case Example

Create a new project called exercise32 or similar (you may have adopted your own naming scheme by now).

Create a C program from the snippet (part of a program) given above.  You will need to create a main() function and put the program inside this. Remember the appropriate #include directives at the top of your program. Look at prior examples if you get stuck remembering which ones you may need. Remember to add another getch(); at the end so that the black console window stays put until you press a key before the program finishes.  

IF vs. Switch..Case

Here's a more complete example of using if vs. using switch.

Just say we have an ordering program where we choose 'M' for main meal, 'D' for dessert, 'S' for Starter and 'X' for exit. To perform the action using an if statement and while loop, we might do this:-  

 
#include <stdio.h>

#include <conio.h>

#include <ctype.h>

#define TRUE 1

main ()

{

  char ch;

  float cost,total;

 

  total = 0.0;

  do

  {

    printf("Choose one of: (S)tarter, (M)ain, (D)essert, e(X)it: ");

    ch=getche(); ch=toupper(ch);

    /* alternatively ch= toupper( getche() ); */

    printf("\n");

    if (ch=='S') {

      printf("Starter included"); cost=3.95;

    } else if (ch=='M') {

      printf("Main included"); cost=8.95;

    } else if (ch=='D') {

      printf("Dessert included"); cost=3.50;

    } else if (ch=='X') {

      printf("Program finished.");

      break;

    } else {

      printf("Incorrect choice. Try again.");

      continue;

    }

    printf("\nCost of choice %c is %4.2f\n", ch, cost);

    total=total+cost;

    printf("Total cost is %5.2f\n\n", total);

  } while (TRUE);

  getch();

}

The continue statement

The continue statement is used with loops - in this case, our do..while loop.  It forces execution to return back to the top of the loop without checking the condition that chooses whether to exit the loop or not - i.e. it ignores the exit condition.

Therefore, if the user presses an incorrect key,  a message is displayed informing the user of this, and execution carries on at the beginning of the loop again (after the do { ).

Exercise 33 - Using if statement to total a menu bill

Type out the above program and run it. Note, this is optional, as it is only to illustrate that you can do the same job as a switch..case in a slightly less clear way using a series of if..else statements - proving again that in programming, there's always several ways of doing the same job - it's just a case of choosing the most appropriate method according to our own judgement.

Exercise 34 - Using switch..case to total a menu bill

And here's the version using the switch() statement:-


#include <stdio.h>

#include <conio.h>

#include <ctype.h>

 

#define TRUE 1

#define STARTER_COST 3.95

#define MAIN_COST 8.95

#define DESSERT_COST 3.50

 

main ()

{

  char ch;

  float cost,total;

 

  total = 0.0;

 

  do

  {

    printf("Choose one of: (S)tarter, (M)ain, (D)essert, e(X)it: ");

    ch=toupper( getche() ); printf("\n");
    switch(ch)

    {

      case('S'): printf("Starter included");

                 cost=STARTER_COST;

                 break;

      case('M'): printf("Main included");

                 cost=MAIN_COST;

                 break;

      case('D'): printf("Dessert included");

                 cost=DESSERT_COST;

                 break;

      case('X'): printf("Program finished");

                 break;

        default: printf("Incorrect choice. Try again\n\n");

                 continue;

    }  /* end of switch */

    printf("\n");

    if (ch=='X') break;

    printf("Cost of choice %c is %4.2f\n", ch, cost);

    total+=cost;

    printf("Total cost is %5.2f\n\n", total);

  } while (TRUE);

 getch();

}
 

Type this into a new project (you may like to copy and paste the program from the previous program to save you time - they are quite similar in many ways).

 A typical output from the program might look like this:-

Choose one of: (S)tarter, (M)ain, (D)essert, e(X)it: s

Starter included

Cost of choice S is 3.95

Total cost is  3.95

 

Choose one of: (S)tarter, (M)ain, (D)essert, e(X)it: m

Main included

Cost of choice M is 8.95

Total cost is 12.90

 

Choose one of: (S)tarter, (M)ain, (D)essert, e(X)it: d

Dessert included

Cost of choice D is 3.50

Total cost is 16.40

 

Choose one of: (S)tarter, (M)ain, (D)essert, e(X)it: p

Incorrect choice. Try again

 



Choose one of: (S)tarter, (M)ain, (D)essert, e(X)it: x

Program finished_

 You may have noticed that when we try to exit the do..while loop if 'X' is chosen, then we run into a prolem. We want to break out of the loop from inside the switch() statement from the case('X') entry-point. However the break command here will not exit the loop - it will exit the switch statement. To get around this, we must check to see if 'X' was chosen using an if statement directly after the closing } of the switch statement, and use break here, which will exit from the while loop (not the switch statement - we have now passed the end of this block of instructions).

So what's the best way to select from multiple options when looking at a single variable?  In general, you should stick to using a switch and several case statements inside the switch.  This makes it more obvious what your program is trying to achieve, despite any minor niggles such as the example given above.

Adding to a variable

There's a few new bits to look at in the above exercise:-

total+=cost;

What does this mean? In the same way as:-

count++;

is the same as:- 

count=count+1;

i.e. it adds 1 to the current value of the count variable.

total+=cost;

is the same as:-

total=total+cost;

I.e. it means add the value of the cost variable to the value of the total variable.

This makes the total variable what is known as an accumulator - i.e. it accumulates a value by having smaller values added onto it.

For example, if total contains 5, and cost contains 3, then total+=cost; would add 3 to 5 and put the result of 8 back into total again.

You can read this as 'add cost to total'.

Similarly,

total-=cost;

would subtract the value of cost from the total variable.

You can use * and / in the same way, but these are of little real use - perhaps:-

total*=2;

to double the contents of the total variable?

Constant values

If you use a value that may change at some time in the future, you may wish to save yourself the hassle of trying to find the value in your program by giving the value a name and substituting the value for the name wherever it appears in the program.

Also, if you use the same value several times in a program, using a substitution method like this means that if you change the value once at the top of the program, you do not need to worry about missing a value by mistake if you need to change it in the future.

One way to do this could be using a variable - e.g.

float starter_cost = 3.95;
...
cost=starter_cost;
...

total+=cost;

 The problem here is that we introduce the possibility of changing the value of starter_cost during the course of the program - it is not really a constant value.

We can use a constant value by using the #define directive at the top of our C program (typically after the #include directives). By placing this at the top of our program, we can see at-a-glance what the constants that could be altered at some future date (e.g. if there were price changes) are that are used within the program. For example:- 

#define STARTER_COST 3.95
...
cost=STARTER_COST;
...

total+=cost;

There are a few things to notice here. The name given is in CAPITAL LETTERS. This is the convention used for constant values in C programs to make them easily identifiable, as opposed to variables which are usually created as lower-case.  Note that this is a convention, which means that you don't have to do it, but it makes your programs more readable to other programmers, and other people's programs more readable to you if you adopt the convention.

Also, the #define statement does not end with a semi-colon, nor have an equals sign. This is because it is a directive, which means that the compiler picks it up and translates it at the pre-processor stage of compilation.

This means that before checking your program is correct, the pre-processor will pick up all #define statements, and build up a list of substitutions to make, and where the keyword appears in the program, it will be substituted for the value you give. 

Exercise 35 - Using #define substitution for constants

Create a program that defines a constant called STARTER_COST so that where this appears in the program, a 3.95 is put in its place.

This means that when the program has finished the pre-processor stage and starts the proper syntax checking (making sure the C instructions are correct) and compilation (converting the C instructions into an object language, to later be converted to machine language by a linker) - the program will look like this:-

#define STARTER_COST 3.95
...
cost=3.95;
...

total+=cost;

 This is why it is a constant value - it cannot be changed once the program has been compiled, because the name you gave has already been turned into constant values inside your program before the program has even been compiled or executed.

Additional Exercise 36 - Stat Finder

Create a new program that does the following:-

In the Next Session...

In the next session we will be covering the following topics:-

(c) Copyright 2002-4 Simon Huggins.   All Rights Reserved.
If you have any issues or questions regarding the content of this web site, please contact the author by clicking here.
Alternatively, you can leave a voice message on 00 44 (0)7050-618-297 or fax on 00 44 (0)7050-618-298

This Page was last updated: 29 January 2004 13:06