C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

statements and nest for statements within other for statements, nesting switch statements is not a
good idea, particularly when the default choices start overlapping. It confuses your compiler, and
the program will not run.


Another note is that, in the first program, you did not enter open and closing braces for the statements
after each case (expression): statement, but here you did. The braces are not needed, but with
more complex blocks of code, the braces can help keep things clear.


Tip

You can replace the repeated code sections in the second-level menus with single lines
of code when you learn to write your own functions later in the book.

The Absolute Minimum
The goal of this chapter was to explain the C switch statement. switch analyzes
the value of an integer or character variable and executes one of several sections of
code called cases. You can write equivalent code using embedded if statements,
but switch is clearer—especially when your program needs to analyze a user’s
response to a menu and execute sections of code accordingly. Key concepts from this
chapter include:


  • Use switch to code menu selections and other types of applications that need to
    select from a variety of values.

  • Use an integer or character value in switch because float and double values
    can’t be matched properly.

  • Put a break statement at the end of each case chunk of code if you don’t want the
    subsequent case statements to execute.

  • Don’t use nested if statements when a switch statement will work instead.
    switch is a clearer statement.

Free download pdf