Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Switch Statement | Introduction to Program Flow
C++ Introduction
course content

Course Content

C++ Introduction

C++ Introduction

1. Getting Started
2. Variables and Data Types
3. Introduction to Operators
4. Introduction to Program Flow
5. Introduction to Functions

bookSwitch Statement

The switch-case construct allows you to compare the result of an expression against a set of predefined values. Structure of switch-case:

cpp

main

copy
123456789101112131415161718
#include <iostream> int main() { int variable = 5; // as the expression to be checked, we will simply have our variable switch (variable) { case 5: //if variable equals 5 std::cout << "Value of variable equals 5" << std::endl; break; case 20://if variable equals 20 std::cout << "Value of variable equals 20" << std::endl; break; } }
  • break - statement means an exit from a block of code;
  • default - is an optional part but a useful one. This part will be executed if none of the cases doesn't fit.

In our case, we check the variable, if it is equal to 5, then the corresponding text will be displayed and, using the break statement, the program flow will leave the entire switch-case construction, and there will be no processing of other cases.

But the switch statement has one caveat. We intentionally remove the break statement:

cpp

main

copy
123456789101112131415161718192021
#include <iostream> int main() { int variable = 5; switch (variable) { case 5: std::cout << "Value of variable equals 5" << std::endl; // delete "break;" case 10: std::cout << "Value of variable equals 10" << std::endl; // delete "break;" case 15: std::cout << "Value of variable equals 15" << std::endl; // delete "break;" } }

Without the break command, the program flow will ignore all the following checks and simply execute the commands of the following cases until it encounters the break statement or the end of the entire switch block.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 3
some-alt