Using switch Statements in C++

By: Emiley J Emailed: 1700 times Printed: 2204 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;
                   break;
case valueTwo: statement;
                   break;
....
case valueN:   statement;
                   break;
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
3:
4:  #include <iostream.h>
5:
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
Excellent!
Masterful!
Incredible!

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;
        break
case 1:
        cout << "One!" << endl;
       break;
case 2:
       cout << "Two!" << endl;
default:
       cout << "Default!" << endl;
}

Example 2

switch (choice)
{
choice 0:
choice 1:
choice 2:
       cout << "Less than 3!";
       break;
choice 3:
       cout << "Equals 3!";
       break;
default:
       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

Comments(30)


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. Java-samples.com totally catered my voracious appetite in java and C++. Thanks for building this tutorial site. More power to java-samples.com 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

ITS GOOD TO UNDERSTAND AS A BEGINNER,
THANK YOU


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.
:D
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 answer..now 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 ";
cin>>price_before_discount;
cout<<"\n\n";


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


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

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

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

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

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

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<conio.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 );
getch();
system("PAUSE");

}

from..shah


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

Hi,
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
Goodbye.


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

CAN I ASK A FORMULA OF FOR MAKING A CALCULATOR USING A SWITCH STATEMENT?u

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

#include<iostream.h>
#include<conio.h>
{
do
{
long date;
char c;
cout<< "enter oyur date ?";
cin>>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";
else
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 in C++
Demonstration of Prefix and Postfix operators in C++
Passing parameters to a function by value in C++
Tutorial on Classes and Members in C++
const Member Functions in C++
Where to Put Class Declarations and Method Definitions in C++
for Loops in C++
Using switch Statements in C++
A Brief History of C++
Difference between Procedural, Structured, and Object-Oriented Programming
C++ and Object-Oriented Programming
Getting Started with C++
Using Comments in a C++ Program
Using functions in C++
How to use Enumerated constants in C++
Most Emailed Articles (in C++)
while (1) Loops in C++
How to handle Exceptions in C++
Character String Literals in C++
Calculating total based on the given quantity and price in C++
A Brief History of C++
Difference between Procedural, Structured, and Object-Oriented Programming
C++ and Object-Oriented Programming
Getting Started with C++
Using cout in C++
Using Comments in a C++ Program
Using functions in C++
How to use Enumerated constants in C++
Demonstration of Prefix and Postfix operators in C++
The if Statement in C++
Advanced if Statements in C++