C switch

The switch statement is used to choose one option from several options. It is a decision making statement. When the value of expression inside the switch is matched to case value then the statements following that case will execute until the break.

Syntax for switch statement:

Flowchart of switch with break keyword:

The operation of switch is shown below in the form of a flowchart for a better understanding.

switch loop

Example:

Output:

Rules for switch statement

  1. The expression inside switch must be of integer or character type.
  2. switch expression cannot be float or double value.
  3. Also, switch expression cannot be NULL or string. But case can be NULL.
  4. The case can be integer constant, a character constant.
  5. The value of case must be of same data type as a value of an expression in the switch.
  6. Cases can never have variable expressions (for example case a +3 : )
  7. break takes the control outside the switch and it is optional
  8. Not every case needs break keyword.
  9. If there is no break then all the cases will be executed after matching case. And this is known as fall-through state of the switch statement.
  10. You cannot use continue keyword in the switch.
  11. Duplication of case is not allowed.
  12. You can have any number of case values.
  13. switch statement has the default case when all other cases are not matched then default statement is executed.
  14. The default case does not require break keyword. The default case is optional.

 

Forms of switch

  • Switch expression cannot be NULL.
  • The switch case value can be NULL.
  • Following examples are valid.

  • Duplication of case value is not allowed.

  • You are also allowed to use char values in cases and switch.
  • Here 10 > 2 is true. Since true means 1 it executes case whose value is 1.

    Output:

    Here also, switch expression is true. And 1 && 1 is equal to 1 i.e. true, hence it will execute.

    Output:
  • At times we may want to execute a common set of statements for multiple cases.
  • Even if there are multiple statements to be executed in each case there is no need to enclose them within a pair of braces (unlike if, and else).
  • Even if a switch expression doesn’t belong to any case the compiler won’t report an error.
Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.