Using switch Statements in C++

By: Emiley J Emailed: 1786 times Printed: 2614 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

if and if/else statements can become quite confusing when nested too deeply, and C++ offers an alternative. Unlike if, which evaluates one value, switch statements allow you to branch on any of a number of different values. The general form of the switch statement is:

switch (expression)
case valueOne: statement;
case valueTwo: statement;
case valueN:   statement;
default:       statement;

expression is any legal C++ expression, and the statements are any legal C++ statements or block of statements. switch evaluates expression and compares the result to each of the case values. Note, however, that the evaluation is only for equality; relational operators may not be used here, nor can Boolean operations.

If one of the case values matches the expression, execution jumps to those statements and continues to the end of the switch block, unless a break statement is encountered. If nothing matches, execution branches to the optional default statement. If there is no default and there is no matching value, execution falls through the switch statement and the statement ends.


NOTE: It is almost always a good idea to have a default case in switch statements. If you have no other need for the default, use it to test for the supposedly impossible case, and print out an error message; this can be a tremendous aid in debugging.

It is important to note that if there is no break statement at the end of a case statement, execution will fall through to the next case statement. This is sometimes necessary, but usually is an error. If you decide to let execution fall through, be sure to put a comment, indicating that you didn't just forget the break.

This C++ program illustrates use of the switch statement.

Demonstrating the switch statement.

1:  //
2:  // Demonstrates switch statement
4:  #include <iostream.h>
6:  int main()
7:  {
8:    unsigned short int number;
9:    cout << "Enter a number between 1 and 5: ";
10:    cin >> number;
11:    switch (number)
12:    {
13:       case 0:   cout << "Too small, sorry!";
14:                 break;
15:       case 5:  cout << "Good job!\n";  // fall through
16:       case 4:  cout << "Nice Pick!\n"; // fall through
17:       case 3:  cout << "Excellent!\n"; // fall through
18:       case 2:  cout << "Masterful!\n"; // fall through
19:       case 1:  cout << "Incredible!\n";
20:                break;
21:       default: cout << "Too large!\n";
22:                break;
23:    }
24:    cout << "\n\n";
25:     return 0;
26: }

Output: Enter a number between 1 and 5: 3

Enter a number between 1 and 5: 8
Too large!

Analysis: The user is prompted for a number. That number is given to the switch statement. If the number is 0, the case statement on line 13 matches, the message Too small, sorry! is printed, and the break statement ends the switch. If the value is 5, execution switches to line 15 where a message is printed, and then falls through to line 16, another message is printed, and so forth until hitting the break on line 20.

The net effect of these statements is that for a number between 1 and 5, that many messages are printed. If the value of number is not 0-5, it is assumed to be too large, and the default statement is invoked on line 21.

The switch Statement

The syntax for the switch statement is as follows:

switch (expression)
case valueOne: statement;
case valueTwo: statement;
case valueN: statement
default: statement;

The switch statement allows for branching on multiple values of expression. The expression is evaluated, and if it matches any of the case values, execution jumps to that line. Execution continues until either the end of the switch statement or a break statement is encountered. If expression does not match any of the case statements, and if there is a default statement, execution switches to the default statement, otherwise the switch statement ends.

Example 1

switch (choice)
case 0:
        cout << "Zero!" << endl;
case 1:
        cout << "One!" << endl;
case 2:
       cout << "Two!" << endl;
       cout << "Default!" << endl;

Example 2

switch (choice)
choice 0:
choice 1:
choice 2:
       cout << "Less than 3!";
choice 3:
       cout << "Equals 3!";
       cout << "greater than 3!";

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

I've been satisfied with your tutorial site. Since I started to learn java and C++, I find it difficult to seek solutions when I encountered problems regarding to syntax and sourcecodes. When I discovered your site, I take my time exploring all links and tutorial stuffs. It was wonderful. Everything is there. totally catered my voracious appetite in java and C++. Thanks for building this tutorial site. More power to Godspeed!!!

View Tutorial          By: Mark Harold F. Manguino at 2008-08-06 05:00:54
2. View Comment

thanks or the infromation about switch statement

View Tutorial          By: mikko at 2008-09-01 23:48:44
3. View Comment

can you give the program about the fast food by using the switch statement.... pls.....

View Tutorial          By: grace at 2008-09-22 00:48:37
4. View Comment

thank you so much i learn from your tutorial i wish ill be expert in programming like you.can you give some example on how to convert and compute at the same time in one program.god bless:

View Tutorial          By: Anonymous at 2009-01-03 20:08:41
5. View Comment

thankx a lot...i've been trying so hard to learn the switch statement ..... this tutorial shined my brain just in 5 mins...thankx again!!!!!

View Tutorial          By: bhuwan at 2009-04-08 23:30:45
6. View Comment

all of codes of t-C++ ide, it is applicable to use to the other C++..?like java?,devc++,and others?

View Tutorial          By: jonard at 2009-06-05 20:41:39
7. View Comment

i like your explanation it is understandable

View Tutorial          By: gerasmia yen-yen d. at 2009-07-15 21:12:39
8. View Comment


View Tutorial          By: Anonymous at 2009-07-24 06:31:50
9. View Comment

your tutorial is very helpful...
i was hoping that you give more example of that within 30-50 lines..

View Tutorial          By: Zero17 at 2009-08-15 09:17:16
10. View Comment

i always encounter a problem every time we discuss new things in my C++ subject.. i don't know if i'm the problem or just my teacher who doesn't explain it clearly and fully.. i have a project now that is needed to include looping, switch and functions in 1code.. sound's easy to some but for me it's hard.. it's making my brain bleed. searching your site, gave me easy problems to solve and also made me understand C++ more...
THANK YOU! even if i don't know you personally.. i owe you my grade.
thanks again

View Tutorial          By: sukira 18 at 2009-08-29 03:25:23
11. View Comment

Thanks for the syntax, this has really helped me understand how to use 'switch'.

View Tutorial          By: Ketobbey at 2010-04-30 19:01:29
12. View Comment

C++ is more than nyc & fun, de most interesting part abt C++ is knowing de algorithim of Ur codes , & u'll b de man. Thax for de explanation of switch statement i don't tink i'l ever have any problem abt switch statement. GOD BLESS U Guys. Dis is de next powerful programmer.

View Tutorial          By: Themba at 2010-09-12 09:11:04
13. View Comment

thank you so much i satisfied for the tutorial in c++..i don't have a problem when you are always give the i know..

View Tutorial          By: flick at 2010-09-24 21:10:59
14. View Comment

I want to ask, can a formula be inserted in this switch statement like the one I provided below?? Really need your help and comment.. Thank you..

#include <iostream>
using namespace std;
int main()
int price_before_discount, RM, dozen, total_price;

cout<< "How much is the price before discount for 1 dozen boxes of tissue?\n";
cout<<"RM ";

cout<< "How many dozen boxes of tissue you buy?\n";

switch (dozen)
total_price = ((price_before_discount*dozen) * (95/100));
case '1': cout<< "Total price is RM ";

total_price = ((price_before_discount*dozen) * (88/100));
case '2': cout<< "Total price is RM ";

total_price = ((price_before_discount*dozen) * (75/100));
case '3': cout<< "Total price is RM ";

total_price = ((price_before_discount*dozen) * (60/100));
case '4' : cout<< "Total price is RM ";

total_price = ((price_before_discount*dozen) * (40/100));
default : cout<< "Total price is RM ";

return 0;

View Tutorial          By: chika at 2011-02-02 17:18:59
15. View Comment

I want inserted switch statement in my program,
Really need your help and comment.. Thank you..

#include <stdio.h>
#include <math.h>

Main () /*calculate maximun stress */

float P, L, w, t;

printf("\t\t\n\n\n <<<This program is to calculate maximum stress>>>\t\n\n\n");
printf("Please input force value, P [KN]: ");
scanf("%f" , &P);
printf("Please input length, L [m]: ");
scanf("%f" , &L);
printf("Please input width, w [cm]: ");
scanf("%f" , &w);
printf("Please input thickness, t [cm]: ");
scanf("%f" , &t);

/* calculate M, y, I */

float M, y, I, max ;

/* convertion */
float w_m, t_m, P_N;
t_m = t /100;
w_m = w /100;
P_N = P * 1000;

/* calculation */

M = P_N * L;
y = t_m /2;
I = (w_m * pow(t_m,3 )) /12 ;
max = (M * y)/ I ;

/* Result */

printf("\n The maximun stress is = %8.3e[pa] or %8.2f[Mpa] \n ", max , max/10000000 );



View Tutorial          By: shah at 2011-02-07 01:11:12
16. View Comment

What should be done to correct the error, just in case instead of a number, the user entered a letter (i.e. letter "a")?

View Tutorial          By: Raymond at 2011-03-07 08:51:54
17. View Comment

thank you
i memorized it easly .

View Tutorial          By: kibrom at 2011-04-27 11:46:24
18. View Comment

thanks for our help. god bless u and again thanks.

View Tutorial          By: mehryab at 2011-05-08 14:44:21
19. View Comment

can we use if statment with swich,,,!!!

View Tutorial          By: dena at 2011-07-09 13:52:27
20. View Comment

please give me a program of the 12 horoscope using the switch statement in functions.

View Tutorial          By: auvx at 2011-08-03 02:02:56
21. View Comment

Thanks a lot for your tutorial.
(: It was very helpful and well-conceived.
And I just loved the last example for it showed how important the breaks are.

View Tutorial          By: Nevermore at 2011-08-03 10:39:32
22. View Comment

3. Write a program that will continuously ask for an integer input from the user until a negative
value is entered. Display the sum and the average of the numbers entered (not including the
negative sentinel value). (Filename: Filename: Exer6.cpp)
Example output:
Please enter number 1? 10
Please enter number 2? 8
Please enter number 3? 3
Please enter number 3? -1
Average is 7.
Computer for sum and average again [Y/N]? N

View Tutorial          By: basil at 2011-08-04 13:00:30
23. View Comment


View Tutorial          By: JUNER at 2011-08-17 03:33:02
24. View Comment

can i ask a program that will compute a order from costumer using switch and do while statement in C++ program

View Tutorial          By: mjae at 2011-09-12 08:02:46
25. View Comment

the tutorial is good and i am satisfied to it i want to learn how to use calender although i made it but i want to have some changes the programe is given below

long date;
char c;
cout<< "enter oyur date ?";
if (date%2==0)
cout<< "the day is monday";
if (date%2==1)
cout<< "the day is tuesday";
if (date%2==2)
cout<< "the day is wednesday";
if (date%2==3)
cout<< "the day is thursday";
if (date%2==4)
cout<< "the day is friday";
if (date%2==5)
cout<< "the day is saturday";
cout<< "you enter invalid date"
while (c !='e')

View Tutorial          By: sheraz at 2011-11-07 02:08:55
26. View Comment

thank's for the info.. i've learned a lot.. now, i better understand the essence of switch statement..

View Tutorial          By: farah talabo at 2012-01-08 23:55:14
27. View Comment

what if i use multiple switch statement, is it works?
what is the code? can u help! please!

View Tutorial          By: earl at 2012-01-29 04:10:25
28. View Comment

you can use multiple switch statements depending on your program, and when there is more than one switch statement, then there is a nested switch am not so sure if am right but that what i think, i also want to know about nested switch pls!!!!!!!!!!

View Tutorial          By: moshood at 2012-04-01 13:24:41
29. View Comment

can I ask question? how to make a complete program to simulate the game jackNpoy? thank you

View Tutorial          By: manuel at 2012-08-13 10:06:24
30. View Comment

can i ask question? on how to make a statement by using a if else statement and switch statement

View Tutorial          By: alas at 2012-09-27 00:42:08

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Emiley J
Password must include both numeric and alphabetic characters - Magento
What is Hadoop?
Returning multiple values from a web service
Tomcat and httpd configured in port 8080 and 80
Java Webservices using Netbeans and Tomcat
Java WebService connected to Database
How to Deploy a Java Web Service
Call a webservice in Java
Java WebService - Create your first web service in Java
package javax.jws does not exist
Getting Started with Android
HTML5 Location - getCurrentPosition() in HTML5
HTML5 Canvas - Using Canvas in HTML5
HTML5 - Introduction
HTML5 Video - Handling video in HTML5

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Using cout.width() in C++
Calculating total based on the given quantity and price in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Dot (.) vs Arrow (->) to access data members in C++
Constructors and Destructors in C++
Calculate average using Two-Dimensional Array in C++
C++ Recursion function explained using Fibonacci series
assert() example program in C++
cin.ignore() in C++
Using peek() and putback() with cin in C++
Programming errors a compiler will detect in C++
Multiple statements in for loops in C++
Using Comments in a C++ Program
Using cout in C++
Sorting an array of Strings in C++
Most Emailed Articles (in C++)
Using cout.width() in C++
Two-Dimensional Array Manipulation in C++
Sorting an array of Strings in C++
Using cout in C++
Printing values in DEBUG mode in C++
File in C++ - Writing text to a file in C++
while loop in C++
Interface Versus Implementation in C++
C++ Sample Program for Allocating, using, and deleting pointers.
How to handle Exceptions in C++
Multiple inheritance example in C++
Vector variables in C++
Using the Built-in Arithmetic Types in C++
Compute the square root of the sum of the squares of an array in C++
Getting Started with C++