C++ - Switch Case Statement
We can write the entire code with if else statements and with out using switch case statement at all. Then why do we need switch case statements? The answer is for program clarity and ease of maintenance.
If we have 2 - 4 cases, then we can use if else statements. If we have more number of cases, then still you can proceed with if else, however it is better to use switch case statements.
switch(key) - switch will take key as an argument. It can be of numeric integer value only (both positive and negative numbers). It can not accept any floating point numbers or strings. It can accept enums as they are treated as integers.
Note: If you do not use break statement after case block, then it will continue executing the next case.
Source Code
int _tmain(int argc, TCHAR* argv[])
{
enum Location {
LocUSA, LocUK, LocGermany, LocIndia, LocChina, LocJapan,
LocPhilippines, LocMalaysia, LocSingapore, LocThailand,
LocIndonesia, LocOthers
};
Location key = LocIndia;
switch(key)
{
case LocUSA:
{
std::cout << "USA";
break;
}
case LocUK:
{
std::cout << "UK";
break;
}
case LocGermany:
{
std::cout << "Germany";
break;
}
case LocIndia:
{
std::cout << "India";
break;
}
case LocChina:
{
std::cout << "China";
break;
}
case LocPhilippines:
{
std::cout << "Philippines";
break;
}
default:
{
std::cout << "Others";
break;
}
};
}
Output
India
|