Menu Close

Articles

C: Selection statement

Selection statement “switch” is a multi-path decision statement based on a variable that can have a specific value. For each value you create a single path to follow. This statement is translated by the compiler into a jump table.

Switch Syntax:

Notes:

  • switch is a block statement;
  • the break is optional statement,
  • statements for each branch do not need brackets: {…}

Rules and restrictions

  • The expression used in a switch statement must have a discrete type, 
  • You can have any number of cases within a switch,
  • The value for each case must be the same data type as the variable in the switch, 
  • When a break statement is reached, the switch terminates,
  • Default section is optional, and is executed if a break is not reached.

Example:

Note:  Now you know switch statement. This statement is not available in Python but is present in many other languages similar to C language: Java, Swift, Go. In all these languages switch is very similar.

Usability:

Switch is useful to create a menu. You can have options 1..9. When user press one of the option a particular branch of program is executed. This can be simulated using “if” statement but is not so readable.

The options can be also char. In this case you can have 25 options, one for each letter of he alphabet. If you use capital letters and numbers you can create a menu with maximum 70 options. This is not always readable. You can improve readability by using an enumeration type.

Enumeration

The enumeration type can be used to create a new data type representing menu options with a name for each option. This type is a discrete type so it can be used in switch statement to create one path for each element of enumeration.

Example:

GoTo Statement

In the previous example we have used goto statement. This is also know as unconditional jump statement. It is advisable to avoid this statement in C programs and use loops instead of jumps to avoid spaghetti code, considered unreadable.

Syntax:

You can jump backward or forward depending on label position. Notice if you have no other control flow statement and you jump backwards the control flow becomes repetitive and the program will never terminate. 

Note: To force program termination in console, you can use Ctrl+Z.

Next article: Repetitive Statement