In this chapter we will understand switch statement.

What is switch statement in C ?

C switch statement helps a variable to compare for equal values. Each values to which the variable is compared is called as the case. When the variable is compared with all the cases and gets no equal match, then it executes the default case.

Below is the switch case syntax in c.

Syntax - switch case
	case expression-to-compared-with  :
		break; // break is optional
	case expression-to-compared-with  :
	default : // default case is optional

In following explains the above switch case statement:

  • expression:

    This is the expression which is compared with all the cases. The constant expression like (1+2*6) is allowed but variable expression like (ab+xy) is not valid.

  • case:

    switch case compares the expression with expression defined in this case statement. You can have any number of case statement in C. Each case is followed by the expression-to-compare-with and a colon (:).

  • expression-to-compared-with:

    This is the expression to which the main expression is compared with. You can have any number of expression-to-compared-with as well.

  • statements:

    When the expression is equals to the expression-to-compared-with, the statement inside the case is executed until the break statement is found.

  • break:

    break statement is used to break the case statement. When the program reaches to break statement it comes out of the switch statement. break statement is optional too, when no break statement is found in a case, the flow of the program continues to next case statements.

  • default:

    default case is executed when expression is matched with none of the cases. There is no break statement required for default statement. The default statement is optional as well. This must be at the end of the switch statement.

Now Lets write a simple switch case example to understand it better.

File name - switch_example.c
void main()
	int number1, number2, choice, result;
	printf("Enter a number ");
	printf("Enter second number ");
	printf("Enter your choice: 1. Addition 2. Subtraction \n");

		case 1:
			printf("Addition \n");
			result = number1 + number2;
		case 2:
			printf("Subtraction \n");
			result = number1 - number2;
			printf("Invalid choice \n");
			result = 0;
	printf("Result is %d", result);
Enter a number 15
Enter second number 5
Enter your choice: 1. Addition 2. Subtraction
Result is 20

In the next chapter we will study about Loops.