Switch in c++ programming
In C++, there is a control flow statement known as the switch statement that offers an effective method of handling numerous situations of a single expression. It allows you to compare the value of an expression to a list of possible constant values and execute code blocks based on the match.
Here is the fundamental syntax of the switch statement in C++:
switch (expression) {
case value1:
// If expression equals value1, run this code.
break;
case value2:
//If expression equals value2, run this code.
break;
// ... more cases ...
default:
//If none of the cases match, run the following code.
}
example:-
#include <iostream>
int main() {
char g = 'B';
switch (g) {
case 'A':
std::cout << "case A" << std::endl;
break;
case 'B':
std::cout << "case B" << std::endl;
break;
case 'C':
std::cout << "case C" << std::endl;
break;
case 'D':
std::cout << "case D." << std::endl;
break;
default:
std::cout << "case default." << std::endl;
}
return 0;
}