What is Switch Statement in C?

Switch statement in C tests the value of a variable and compares it with multiple cases. Once the instance lucifer is found, a block of statements associated with that detail instance is executed.

Each case in a block of a switch has a unlike name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the lucifer is plant.

If a case match is NOT plant, and then the default statement is executed, and the command goes out of the switch block.

In this tutorial, yous will learn-

  • What is Switch Argument in C?
  • Switch Case Syntax
  • Switch Argument Flowchart
  • Switch Case Example in C
  • Nested Switch in C
  • Why do nosotros need a Switch example?
  • Rules for switch statement

Switch Case Syntax

A general syntax of how switch-case is implemented in a 'C' programme is as follows:

switch( expression ) { 	case value-ane: 			Block-one; 			Break; 	example value-2: 			Cake-two; 			Pause; 	case value-n: 			Block-n; 			Break; 	default: 			Cake-1; 			Break; } Statement-ten;
  • The expression can exist integer expression or a graphic symbol expression.
  • Value-ane, 2, n are case labels which are used to identify each instance individually. Remember that case labels should not be same as it may create a problem while executing a programme. Suppose we accept 2 cases with the aforementioned label equally '1'. And so while executing the programme, the case that appears get-go will be executed fifty-fifty though y'all want the program to execute a 2nd example. This creates problems in the program and does not provide the desired output.
  • Case labels always end with a colon ( : ). Each of these cases is associated with a block.
  • A cake is nothing but multiple statements which are grouped for a particular case.
  • Whenever the switch is executed, the value of examination-expression is compared with all the cases which nosotros have defined inside the switch. Suppose the exam expression contains value 4. This value is compared with all the cases until case whose label four is found in the plan. As soon as a case is found the block of statements associated with that particular case is executed and control goes out of the switch.
  • The intermission keyword in each case indicates the end of a particular instance. If nosotros do not put the break in each example and then even though the specific instance is executed, the switch in C volition continue to execute all the cases until the end is reached. This should non happen; hence we always take to put intermission keyword in each instance. Break will terminate the case once it is executed and the control will fall out of the switch.
  • The default case is an optional one. Whenever the value of test-expression is not matched with whatever of the cases inside the switch, then the default will be executed. Otherwise, it is not necessary to write default in the switch.
  • Once the switch is executed the control will go to the argument-x, and the execution of a program will continue.

Switch Statement Flowchart

Following diagram illustrates how a case is selected in switch case:

Switch Statement Flowchart
How Switch Works

Switch Case Instance in C

Following programme illustrates the apply of switch:

#include <stdio.h>     int main() {         int num = 8;         switch (num) {             case 7:                 printf("Value is 7");                 interruption;             case 8:                 printf("Value is viii");                 break;             case ix:                 printf("Value is 9");                 suspension;             default:                 printf("Out of range");                 interruption;         }         return 0;     }

Output:

Value is 8                

Switch Statement Flowchart

  1. In the given program nosotros have explain initialized a variable num with value viii.
  2. A switch construct is used to compare the value stored in variable num and execute the block of statements associated with the matched example.
  3. In this program, since the value stored in variable num is eight, a switch will execute the case whose case-label is 8. Later on executing the example, the control will fall out of the switch and program will be terminated with the successful result by printing the value on the output screen.

Endeavour changing the value of variable num and discover the change in the output.

For case, nosotros consider the following plan which defaults:

#include <stdio.h> int main() { int language = 10;   switch (language) {   case 1:     printf("C#\northward");     break;   instance ii:     printf("C\northward");     break;   case 3:     printf("C++\n");     break;   default:     printf("Other programming linguistic communication\due north");}}

Output:

Other programming linguistic communication

When working with switch case in C, you group multiple cases with unique labels. You need to innovate a break statement in each case to branch at the cease of a switch statement.

The optional default case runs when no other matches are made.

Nosotros consider the post-obit switch statement:

#include <stdio.h> int principal() { int number=v; switch (number) {   case ane:   case ii:   instance iii:     printf("One, Two, or Three.\northward");     break;   case 4:   case v:   case vi:     printf("Four, Five, or Six.\north");     break;   default:     printf("Greater than Six.\n");}}

Output:

Four, 5, or Vi.

Nested Switch in C

In C, we can have an inner switch embedded in an outer switch. Too, the case constants of the inner and outer switch may accept common values and without any conflicts.

We considere the following plan which the user to type his own ID, if the ID is valid it will ask him to enter his password, if the password is right the program will print the proper name of the user, otherwise ,the program volition print Wrong Password and if the ID does not exist , the program will print Incorrect ID

#include <stdio.h> int main() {         int ID = 500;         int password = 000;         printf("Plese Enter Your ID:\n ");         scanf("%d", & ID);         switch (ID) {             instance 500:                 printf("Enter your password:\n ");                 scanf("%d", & password);                 switch (password) {                     case 000:                         printf("Welcome Beloved Programmer\n");                         interruption;                     default:                         printf("incorrect countersign");                         break;                 }                 break;             default:                 printf("incorrect ID");                 intermission;         } }

OUTPUT:

Plese Enter Your ID:  500 Enter your countersign:  000 Welcome Love Programmer                

Nested Switch in C

  1. In the given program we have explained initialized two variables: ID and countersign
  2. An outer switch construct is used to compare the value entered in variable ID. Information technology execute the cake of statements associated with the matched case(when ID==500).
  3. If the block statement is executed with the matched example, an inner switch is used to compare the values entered in the variable password and execute the statements linked with the matched example(when password==000).
  4. Otherwise, the switch case will trigger the default case and impress the advisable text regarding the plan outline.

Why practise nosotros need a Switch case?

At that place is one potential trouble with the if-else statement which is the complexity of the program increases whenever the number of alternative path increases. If you use multiple if-else constructs in the program, a program might become difficult to read and comprehend. Sometimes it may even confuse the programmer who himself wrote the program.

The solution to this trouble is the switch statement.

Rules for switch statement

  • An expression must always execute to a outcome.
  • Instance labels must be constants and unique.
  • Instance labels must cease with a colon ( : ).
  • A break keyword must be present in each example.
  • At that place tin exist only 1 default label.
  • We can nest multiple switch statements.

Summary

  • A switch is a decision making construct in 'C.'
  • A switch is used in a plan where multiple decisions are involved.
  • A switch must contain an executable exam-expression.
  • Each case must include a suspension keyword.
  • Case characterization must be constants and unique.
  • The default is optional.
  • Multiple switch statements can be nested inside one another.