Menu
C++ Tutorials

C++

Switch Statement



Tutorials > C++ > Switch Statement

View Full Source

Introduction

You may have thought that it could get quite tiring when trying to make a decision based on a great number of categories ie. having a large number of if else statements.

The switch statement can be used to simplify this process.

Contents of main.cpp :


#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
	int choice;

The statements below output a menu and allow the user to enter a selection.

	cout << "Menu" << endl;
	cout << "----" << endl;
	cout << "1) Choice 1" << endl;
	cout << "2) Choice 2" << endl;
	cout << "3) Choice 3" << endl;
	cout << endl;
	cout << "Please enter choice : ";

	cin >> choice;

The switch statement takes the form :

    switch(value)

followed by a number of case sections

The value in the switch statement is checked to see if it equals any of the values shown after each case keyword. If it is, the code next to that case statement is executed. A : is placed after the case keyword, followed by the value you are comparing.

Another keyword is the break keyword. This is used to step out of the switch statement. This is placed at the end of the section of code you are wanting to execute.

The default keyword is used to specify what should happen if none of the case values match the value at the top of the switch statement.

	// Switch Statement
	//------------------
	switch(choice)
	{
	case 1 : 
		cout << "You chose choice 1" << endl;
		break;
	case 2 :
		cout << "You chose choice 2" << endl;
		break;
	case 3 :
		cout << "You chose choice 3" << endl;
		break;
	default :
		cout << "You entered a wrong selection" << endl;
		break;
	}

	cout << endl;

The code below shows what will happen if no breaks are used. If the user enters a 2, all code under case 2 : will be executed and then the code under case 3 will execute and so on.
Please run the code given to see the effect.

	// Problem with no breaks
	//------------------------
	switch(choice)
	{
	case 1 : 
		cout << "You chose choice 1" << endl;
	case 2 :
		cout << "You chose choice 2" << endl;
	case 3 :
		cout << "You chose choice 3" << endl;
	default :
		cout << "You entered a wrong selection" << endl;
	}

	system("pause");

	return 0;
}

You should now be able to use the switch statement to layout your code more efficiently when wanting to make a decision depending on the value of a particular expression or variable.

Please also note that if you want to declare and initialize a variable within a case section, you need to enclose the code within a code block ie. using { and }

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 13 - If Statement Tutorial 15 - While Loop >

Back to Top


All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer

Links