C++ Switch
Published Aug 3, 2021Updated May 23, 2025
Contribute to Docs
A switch statement provides a means of checking an expression against various case statements. If there is a match, the code within starts to execute. The break keyword can be used to terminate a case.
There’s also an optional default statement marking code that executes if none of the case statements are true.
Syntax
A switch statement looks like:
switch (grade) {case 9:std::cout << "Freshman\n";break;case 10:std::cout << "Sophomore\n";break;case 11:std::cout << "Junior\n";break;case 12:std::cout << "Senior\n";break;default:std::cout << "Invalid\n";break;}
- The
switchkeyword initiates the statement and is followed by(), which contains the value that each case will compare. In the example, the value or expression of the switch statement isgrade. One restriction on this expression is that it must evaluate to an integral type (int,char,short,long,long long, orenum). - Inside the block,
{}, there are multiple cases. - The
casekeyword checks if the expression matches the specified value that comes after it. The value following the first case is9. If the value of grade is equal to9, then the code that follows the:would run. - The
breakkeyword tells the computer to exit the block and not execute any more code or check any other cases inside the code block. - At the end of each switch statement, there is a
defaultstatement. If none of the cases aretrue, then the code in thedefaultstatement will run.
In the code above, suppose grade is equal to 10, then the output would be “Sophomore”.
Note: Without the
breakkeyword at the end of each case, the program would execute the code for the first matching case and all subsequent cases, including thedefaultcode. This behavior is different fromif/elseconditional statements which execute only one block of code.
Codebyte Example
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours