0% found this document useful (0 votes)
85 views6 pages

7.4 - Switch Statement Basics - Learn C++

The document discusses switch statements in C++. It explains that switch statements provide an alternative to chained if-else statements when evaluating a variable against a set of values. A switch statement evaluates an expression once and allows branching to different blocks of code based on case labels that match the expression's value. It also supports a default case if no other case matches. Using switch statements makes code more efficient and readable compared to chained if-else statements.

Uploaded by

Bias Hacker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views6 pages

7.4 - Switch Statement Basics - Learn C++

The document discusses switch statements in C++. It explains that switch statements provide an alternative to chained if-else statements when evaluating a variable against a set of values. A switch statement evaluates an expression once and allows branching to different blocks of code based on case labels that match the expression's value. It also supports a default case if no other case matches. Using switch statements makes code more efficient and readable compared to chained if-else statements.

Uploaded by

Bias Hacker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

LEARN C++

Skill up with our free tutorials

7.4 — Switch statement basics


 ALEX1  SEPTEMBER 15, 2022

Although it is possible to chain many if-else statements together, this is both difficult to read and inefficient.
Consider the following program:

COPY
1 #include <iostream>

3 void printDigitName(int x)

4 {

5 if (x == 1)

6 std::cout << "One";

7 else if (x == 2)

8 std::cout << "Two";

9 else if (x == 3)

10 std::cout << "Three";

11 else

12 std::cout << "Unknown";

13 }

14

15 int main()

16 {

17 printDigitName(2);

18 std::cout << '\n';

19

20 return 0;

21 }

While this example isn’t too complex, x is evaluated up to three times (which is inefficient), and the reader has to be
sure that it is x being evaluated each time (not some other variable).

Because testing a variable or expression for equality against a set of different values is common, C++ provides an
alternative conditional statement called a switch statement that is specialized for this purpose. Here is the same
program as above using a switch:
1 #include <iostream>

3 void printDigitName(int x)

4 {

5 switch (x)

6 {

7 case 1:

8 std::cout << "One";

9 return;

10 case 2:

11 std::cout << "Two";

12 return;

13 case 3:

14 std::cout << "Three";

15 return;

16 default:

17 std::cout << "Unknown";

18 return;

19 }

20 }

21

22 int main()

23 {

24 printDigitName(2);

25 std::cout << '\n';

26

27 return 0;

28 }

The idea behind a switch statement is simple: an expression (sometimes called the condition ) is evaluated to
produce a value. If the expression’s value is equal to the value after any of the case labels , the statements after
the matching case label are executed. If no matching value can be found and a default label exists, the
statements after the default label are executed instead.

Compared to the original if statement , the switch statement has the advantage of only evaluating the
expression once (making it more efficient), and the switch statement also makes it clearer to the reader that it is
the same expression being tested for equality in each case.

Best practice
Prefer switch statements over if-else chains when there is a choice.

Let’s examine each of these concepts in more detail.

Starting a switch
We start a switch statement by using the switch keyword, followed by parentheses with the conditional
expression that we would like to evaluate inside. Often the expression is just a single variable, but it can be any valid
expression.

The one restriction is that the condition must evaluate to an integral type (see lesson 4.1 -- Introduction to
fundamental data types (https://www.learncpp.com/cpp-tutorial/introduction-to-fundamental-data-types/)2 if you need a reminder
which fundamental types are considered integral types) or an enumerated type (covered in future lesson 10.2 --
Unscoped enumerations (https://www.learncpp.com/cpp-tutorial/unscoped-enumerations/)3), or be convertible to one.
Expressions that evaluate to floating point types, strings, and most other non-integral types may not be used here.

For advanced readers


Why does the switch type only allow for integral (or enumerated) types? The answer is because switch
statements are designed to be highly optimized. Historically, the most common way for compilers to implement
switch statements is via Jump tables (https://en.wikipedia.org/wiki/Branch_table)4 -- and jump tables only work with
integral values.

For those of you already familiar with arrays, a jump table works much like an array, an integral value is used as
the array index to “jump” directly to a result. This can be much more efficient than doing a bunch of sequential
comparisons.

Of course, compilers don’t have to implement switches using jump tables, and sometimes they don’t. There is
technically no reason that C++ couldn’t relax the restriction so that other types could be used as well, they just
haven’t done so yet (as of C++20).

Following the conditional expression, we declare a block. Inside the block, we use labels to define all of the values we
want to test for equality. There are two kinds of labels.

Case labels
The first kind of label is the case label, which is declared using the case keyword and followed by a constant
expression. The constant expression must either match the type of the condition or must be convertible to that type.

If the value of the conditional expression equals the expression after a case label , execution begins at the first
statement after that case label and then continues sequentially.

Here’s an example of the condition matching a case label :

1 #include <iostream>

3 void printDigitName(int x)

4 {

5 switch (x) // x is evaluated to produce value 2

6 {

7 case 1:

8 std::cout << "One";

9 return;

10 case 2: // which matches the case statement here

11 std::cout << "Two"; // so execution starts here

12 return; // and then we return to the caller

13 case 3:

14 std::cout << "Three";

15 return;

16 default:

17 std::cout << "Unknown";

18 return;

19 }

20 }

21

22 int main()

23 {

24 printDigitName(2);

25 std::cout << '\n';

26

27 return 0;

28 }

This code prints:

Two

In the above program, x is evaluated to produce value 2 . Because there is a case label with value 2 , execution
jumps to the statement underneath that matching case label. The program prints Two , and then the return
statement is executed, which returns back to the caller.

There is no practical limit to the number of case labels you can have, but all case labels in a switch must be unique.
That is, you can not do this:

1 switch (x)

2 {

3 case 54:

4 case 54: // error: already used value 54!

5 case '6': // error: '6' converts to integer value 54, which is already used

6 }

The default label


The second kind of label is the default label (often called the default case), which is declared using the default
keyword. If the conditional expression does not match any case label and a default label exists, execution begins at
the first statement after the default label.

Here’s an example of the condition matching the default label:

1 #include <iostream>

3 void printDigitName(int x)

4 {

5 switch (x) // x is evaluated to produce value 5

6 {

7 case 1:

8 std::cout << "One";

9 return;

10 case 2:

11 std::cout << "Two";

12 return;

13 case 3:

14 std::cout << "Three";

15 return;

16 default: // which does not match to any case labels

17 std::cout << "Unknown"; // so execution starts here

18 return; // and then we return to the caller

19 }

20 }

21

22 int main()

23 {

24 printDigitName(5);

25 std::cout << '\n';

26

27 return 0;

28 }

This code prints:

Unknown

The default label is optional, and there can only be one default label per switch statement. By convention, the
default case is placed last in the switch block.

Best practice
Place the default case last in the switch block.

Taking a break
In the above examples, we used return statements to stop execution of the statements after our labels. However,
this also exits the entire function.

A break statement (declared using the break keyword) tells the compiler that we are done executing statements
within the switch, and that execution should continue with the statement after the end of the switch block. This
allows us to exit a switch statement without exiting the entire function.

Here’s a slightly modified example rewritten using break instead of return :

1 #include <iostream>

3 void printDigitName(int x)

4 {

5 switch (x) // x evaluates to 3

6 {

7 case 1:

8 std::cout << "One";

9 break;

10 case 2:

11 std::cout << "Two";

12 break;

13 case 3:

14 std::cout << "Three"; // execution starts here

15 break; // jump to the end of the switch block

16 default:

17 std::cout << "Unknown";

18 break;

19 }

20

21 // execution continues here

22 std::cout << " Ah-Ah-Ah!";

23 }

24

25 int main()

26 {

27 printDigitName(3);

28 std::cout << '\n';

29

30 return 0;

31 }

The above example prints:

Three Ah-Ah-Ah!

Best practice
Each set of statements underneath a label should end in a break statement or a return statement . This
includes the statements underneath the last label in the switch.

So what happens if you don’t end a set of statements under a label with a break or return ? We’ll explore that
topic, and others, in the next lesson.
Next lesson
 7.5 Switch fallthrough and scoping
5

 Back to table of contents


6

Previous lesson
 7.3 Common if statement problems
7

B U URL INLINE CODE C++ CODE BLOCK HELP!

Leave a comment...

 biashackerdeep
Notify me about replies:   
 souradeep.exe@gmail.com  POST COMMENT

 Find a mistake? Leave a comment! 

Avatars from https://gravatar.com/11 are connected


to your provided email address.

495 COMMENTS Newest


Mohamed
 September 8, 2022 11:13 pm

I want to ask u a question outside of the scope of this lesson.


From your point of view, when do I start acquiring the skill "problem solving" ?!
ty for reply in advance, and I want your answer as soon as possible for you ☺

0 Reply

Alex Author

 Reply to 
Mohamed
12  September 14, 2022 2:19 pm

You might also like