How to Create a Switch Statement in C

Use the Switch statement in C to evaluate a large number of values for a single variable or expression. Switch can be much tidier than a long string of If Else statements.

Instructions

  1. Create a Switch Statement

    • 1

      Choose the value that will determine an action in your Switch statement. It can be a single variable, the result of a function call or any expression.

    • 2

      Place this value or expression after the switch statement like this:

      switch (variable) {
    • 3

      Make a list of all the values you want to catch. Note that it's possible for multiple values to have the same action, but you can't use ranges, just lists of values. For example, you can't have a case for values from 301 to 400, unless you want to list all 100 values one by one!

    • 4

      Know that it's very common for the values to be constants defined with the #define C precompiler statement.

    • 5

      Add a case statement for each value in the following format:

       case value:
    • 6

      Follow each case statement with one or more actions. Unlike most C structures, you don't need curly brackets for multiple statements.

    • 7

      Conclude each set of commands with a break statement before beginning the next case. If you don't do this, execution will "fall through" into the next case, which is virtually never desirable. It's O.K. to leave out the break if something else (like a return statement) ensures it will never "fall through."

    • 8

      Create a special default case to catch anything not matched by an earlier case. It's just default, not case default.

    • 9

      Conclude the block with a }, as in this complete example:

      switch (evaluate_color(red, green, blue)) {
      case RED:
      printf("A brilliant red sunset fills the sky.\n");
      x = 11;
      break;
      case YELLOW:
      printf("The sun beats down mercilessly.\n");
      x = 14;
      break;
      case GREEN:
      x = 10;
      evaluate_green();
      break;
      case BLUE:
      printf("Congratulations, you win!\n");
      return;
      default:
      printf("Nothing special happens.\n");
      break;
      }

Tips & Warnings

  • Switch will only work if all the comparisons are against a single variable or expression. Otherwise, create an If Else statement with multiple Else Ifs.

  • Using "fall through" is generally considered a bad technique and should be avoided unless you're absolutely certain that your code will be both correct and readable.

Related Searches:

Comments

You May Also Like

Related Ads

Featured