Programming in C: Switch Case Statements

The switch case statement in C is a substitute for a long if statement that compare integer values. Here is the general form for a switch case:

switch (variable_name)
{
case value_1:
/* Code to execute if variable_name == value_1 */
break;
case value_2:
Code to execute if variable_name == value_2
break;
...
case value_n:
Code to execute if variable_name == value_n
break;
default:
/* Code to execute if <variable> does not equal the value following any of the cases. */
break;
}

The condition in a switch statement is a value, typically an integer. If the value in the case matches the switch value, then whatever code appears after the colon. A break statement is used to exit the switch case statement. Here is a practical example of a switch case statement:

#include <stdio.h>

void playgame()
{
printf( "Play game called" );
}
void loadgame()
{
printf( "Load game called" );
}
void playmultiplayer()
{
printf( "Play multiplayer game called" );
}
	
int main()
{
int input;

printf("1. Play game\n");
printf("2. Load game\n");
printf("3. Play multiplayer\n");
printf("4. Exit\n");
printf("Selection: ");
scanf("%d", &input);
switch (input) 
  {
case 1:
playgame();
break;
case 2:
loadgame();
break;
case 3: 
playmultiplayer();
break;
case 4:
printf("Thanks for playing!\n");
break;
default:
printf("Bad input, quitting!\n");
break;
}
return 0;

}

More tutorials coming soon! Let me know how you like the tutorials by commenting below and if there is any specific topics or languages you would like covered. Follow me on Twitter to keep up-to-date on all the latest news and tutorials.

Programming Tutorials: Reader Suggestions

Programming in C: Functions