Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying The C++ Workshop
  • Table Of Contents Toc
The C++ Workshop

The C++ Workshop

By : Dale Green , Kurt Guntheroth , Shaun Ross Mitchell
5 (8)
close
close
The C++ Workshop

The C++ Workshop

5 (8)
By: Dale Green , Kurt Guntheroth , Shaun Ross Mitchell

Overview of this book

C++ is the backbone of many games, GUI-based applications, and operating systems. Learning C++ effectively is more than a matter of simply reading through theory, as the real challenge is understanding the fundamentals in depth and being able to use them in the real world. If you're looking to learn C++ programming efficiently, this Workshop is a comprehensive guide that covers all the core features of C++ and how to apply them. It will help you take the next big step toward writing efficient, reliable C++ programs. The C++ Workshop begins by explaining the basic structure of a C++ application, showing you how to write and run your first program to understand data types, operators, variables and the flow of control structures. You'll also see how to make smarter decisions when it comes to using storage space by declaring dynamic variables during program runtime. Moving ahead, you'll use object-oriented programming (OOP) techniques such as inheritance, polymorphism, and class hierarchies to make your code structure organized and efficient. Finally, you'll use the C++ standard library?s built-in functions and templates to speed up different programming tasks. By the end of this C++ book, you will have the knowledge and skills to confidently tackle your own ambitious projects and advance your career as a C++ developer.
Table of Contents (15 chapters)
close
close

switch/case

As we've seen, we can use if/else to perform certain actions based on which conditions are true. This is great when you're evaluating multiple conditional statements to determine flow, such as the following:

    if (checkThisCondition)
    {
        // Do something ...
    }
    else if (checkAnotherCondition)
    {
        // Do something else ...
    }

When we're evaluating the different possibilities of a single variable, however, we have a different statement available to us: the switch statement. This allows us to branch in a similar way to an if/else statement, but each branch is based on a different possible value of a single variable that we're switching on.

A good example of where this would be suitable is the menu application we created in the previous exercise. Currently, we chain if/else statements to handle the different possible values, but since we're switching on a single variable (the menu index), it would be more suitable as a switch statement.

A basic implementation of a switch statement block is as follows:

    switch (condition)
    {
        case value1:
            // Do stuff.
        break;
        case value2:
            // Do stuff.
        break;
        default:
            // Do stuff.
        break;
    }

Applying this to the previous menu example, the condition would be the selected menu index that we read from our user, and the different values would be our supported possibilities (1-3). The default statement would then catch the cases where the user inputs an option that we're not handling. We could print an error message in those cases and have them select a different option.

A switch statement comprises a number of keywords:

  • switch: This denotes the condition that we're evaluating. We're going to switch our behavior based on its value.
  • case: Each case statement is followed by the value that we want to handle. We can then define our behavior for that scenario.
  • break: This statement signals the end of our code for that given case. More on these in the next topic.
  • default: This is the default case and is what will get called should none of the other cases match.

    Note

    A default case is not required but is recommended. It allows us to handle all other values, perhaps throwing an exception.

An important limitation of switch statements is that they can only be used with certain types. These are whole numbers and enum values. This means that, for example, we couldn't use either string or float types within a switch statement.

Note

Enumerated type, or enum, is a user-generated data type in C++. A detailed discussion on this is beyond the scope of this book. However, you can refer to the following documentation for further details: https://packt.live/35l6QWT.

It's also worth noting that not every case needs a break statement. They are optional, though will likely be required in the vast majority of cases. If the break statement is omitted, however, then the flow of execution will continue to the next case statement until a break is hit. Be careful here because missing break statements is a common cause of hard-to-find bugs; ensuring each case has a break statement where needed could save you lots of potential debugging time down the line.

Perhaps the best way to see the use of a switch statement is to convert some if/else chains to switch statements. This will be the objective of the following exercise.

Exercise 7: Refactor an if/else Chain into switch/case

In this exercise, we will reuse the code from the previous exercise and refactor it into a switch statement. This will clearly show how we can represent the same functionality using either method. Since we're only checking the different possible values of a single variable, however, a switch statement is preferred.

Note

Ensure that you have copied the code from the previous exercise (steps 1-2) in the compiler window. The complete code can be found here: https://packt.live/32ZZ5Ek.

We will break this down into a number of simple steps:

  1. First, the variable we're checking here is number, so that's going to be the condition that we're switching on. Add that to a switch statement and open our curly brackets ready for the rest of the switch block:
        switch (number)
        {
  2. Next, we'll convert our first if statement into a case statement. If we look at the first one, we're checking whether number is equal to 1. Add this as our first case value and copy the output into the case body:
        case 1:
            std::cout << "Fries: $0.99\n";
        break;
  3. Now, repeat this for each of the if statements, apart from the last one. If you remember, this statement had no condition that it checked; it's simply the last option. This meant that if all other checks failed, execution would fall right through to that final default statement. This is exactly how the default case works, so we will end by moving that else statement into a default case. We should end up with the following switch statement, which will replace our if/else chain:
        switch (number)
        {
            case 1:
                std::cout << "Fries: $0.99\n";
            break;
            case 2:
                std::cout << "Burger: $1.25\n";
            break;
            case 3:
                std::cout << "Shake: $1.50\n";
            break;
            default:
                std::cout << "Invalid choice.";
            break;
        }

    This statement is functioning the same as the chained if/else, so you could use either; however, you generally see switch statements over long if chains. Now, let's run this code and check that it's behaving how we'd expect.

  4. The complete code looks like this:
    // if/else to switch/case
    #include <iostream>
    #include <string>
    int main() 
    {
        std::string input;
        int number;
        std::cout << "Menu\n";
        std::cout << "1: Fries\n";
        std::cout << "2: Burger\n";
        std::cout << "3: Shake\n";
        std::cout << "Please enter a number 1-3 to view an item price: ";
        getline(std::cin, input);
        number = std::stoi(input);
        switch (number) 
        {
        case 1:
            std::cout << "Fries: $0.99\n";
        break;
        case 2:
            std::cout << "Burger: $1.25\n";
        break;
        case 3:
            std::cout << "Shake: $1.50\n";
        break;
        default:
            std::cout << "Invalid choice.";
        break;
        }
    }
  5. Run the complete code. You will obtain an output that's similar to the following:
Figure 2.3: The code works the same, but this time presented as a switch statement

Figure 2.3: The code works the same, but this time presented as a switch statement

The program behaves in the same way but is arguably neater and easier to follow. We can clearly see each possible behavior branch and the case that will let it execute.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
The C++ Workshop
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon