Skip to content

The Switch Statement

Chapter 4

Instead of an if…else, use a switch statement whenever comparing single value with multiple discrete values (i.e., instead of an if with the == operator).

Here is the syntax:

cpp
switch (thing to switch on)
{
    case thing1:
        //do this;
        break;
    case thing2:
        //do this;
        break;
    default:
        //do everything else;
}
Try the following code from the video.
cpp
/*
 * Given a month of the year, calculates the number of days in that month.
 * by Dr. Hayes
 */

#include <iostream>
using namespace std;

int main()
{
	int month;
	int days;
	int year;

	// Get the month number
	cout << "Enter the month number: ";
	cin >> month;
	cout << endl;

	// Check for invalid months
	if (month <= 0 || month > 12)
	{
		cout << month << " is NOT a valid month (between 1 and 12)"
			<< endl;
		return 0;
	}

	// Calculate the number of days in the month
	switch (month)
	{
		case 0:
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
			days = 31;
			break;
		case 2:
			cout << "Enter the year: ";
			cin >> year;
			cout << endl;

			// Note: Leap days occur in February every 4 years, except for
			//       years that are divisible by 100, but not by 400.
			if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
			{
				days = 29;
			}
			else
			{
				days = 28;
			}
			break;
		default:
			days = 30;
	}

	
	// Display the number of days in this month
	cout << "There are " << days << " days in that month." << endl;

	return 0;
}

Example

cpp
// grade is an int
switch (grade / 10)
{
	case 10:
	case 9:
		letter = 'A';
		break;
	case 8:
		letter = 'B';
		break;
	case 7:
		letter = 'C';
		break;
	case 6:
		letter = 'D';
		break;
	default:
		letter = 'F';
}

Self-Check Questions

  1. When should you use a switch statement instead of an if…else statement?
  2. Give two examples of data types that cannot be used in switch statements in C++.