C++ Switch Case - An Overview
Introduction:
In C++, the "switch case" statement is a powerful control structure that allows programmers to execute different blocks of code based on the value of an expression or variable. It provides a concise and efficient way to handle multiple conditional branches, enhancing code readability and maintainability.
Syntax:
The basic syntax of the C++ switch case statement is as follows:
cppswitch (expression) {
case value1:
// Code block for case value1
break;
case value2:
// Code block for case value2
break;
// Additional case statements as needed
default:
// Code block for handling default case (optional)
break;
}
Explanation:
- The
expression
is evaluated once, and its value is compared to eachcase
constant. - If a match is found between the
expression
value and acase
constant, the corresponding code block is executed until thebreak
statement is encountered. - If there is no match, and a
default
case is provided, the code inside thedefault
block will be executed. Thedefault
case is optional.
Example:
cpp#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
case 4:
std::cout << "Thursday" << std::endl;
break;
case 5:
std::cout << "Friday" << std::endl;
break;
default:
std::cout << "Weekend" << std::endl;
break;
}
return 0;
}
0 Comments