C Programming

switch

Posted on 06th June 2013

The switch statement is another form of branching control statement. switch statement can branch to a number of different execution paths in a program. The same could be achieved using nested if ... else statement but switch offers a better approach. However unlike if ... else, the switch statement works only with integer or character type data.

The switch statement is written as

switch (int or char)
{
	case constant : 
		statement;
	break;
	......
	......
	default:
		statement;
	break; 
}

It takes an integer or character variable or expression and chose from one of the several different cases whose constant value matches the evaluated expression.

When a matching case is encountered, it will execute all the statement below it until the break statement.

The break statement is optional, but if it is omitted the execution will continue until the end of the switch statement (closing curly braces).

You can also add a default case which is optional. The statements below this default case would be executed if no match is found in any of the cases.

Example

Here is a program which takes a user input and prints the corresponding message.

#include <stdio.h>

int main() {
int option;

printf("Press 1, 2 or 3 :");
scanf("%d",&option);

switch (option)
	{
	case 1: 
		printf("You have selected option ONE");
		break;
	case 2: 
		printf("You have selected option TWO");
		break;
	case 3: 
		printf("You have selected option THREE");
		break;
	default:
		printf("You have selected an invalid option");
		break;
}

return 0;
}

Post a comment

Comments

Nothing yet..be the first to share wisdom.