Switch statements are sometimes referred to case statements depending on the website, book, or fellow devolper you speak to. Below I will discuss the four main keywords used in the case statements and show you sample code that utilizes the four. The four keywords used in case statements are, switch, break, default, and case switch:
The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values and does commands accordingly.
Syntax: switch ( expression )
Ex: switch ( control )
case 1:
{
cout << "you have full control\n";
break;
}
break:
Break statements are used to immediately exit from the switch statement blocks. It will jump down paste the ending bracket of the of the switch statement. Break and return are the common ways for exiting switch statements.
Syntax: break;
Ex: case 2:
{
printf("you said hi %d times\n", count);
break;
}
default:
Although the default is optional, it is recommended to use it for debugging purposes. It can be used to test for the impossible case and print out an error message. Using default is a simple error trap for any values that aren't in the case statements.
Syntax: default:
Ex: default:
{ /* code here */ }
case:
The case keyword is used in tandem with the switch statement. They're used to limit the available choice(s) the user can input. The possible choices (values) the user may input is based off the case statements.
Syntax: case constant_int:
Ex: case 2:
{ /* code here */ }
Below is a piece of a program that utilizes a menu with switch statements:
menu(); /* a user-defined function that displays a menu for the user to select from */ cout << "Enter your selection: "; cin >> men;
switch (men) {
case 1: { cout << "\nComputer Name: " << cpu << "\n\n"; } break;
case 2: { cout << "\nID Number: " << idn << "\n\n"; } break;
case 3: { cout << "\nMAC Address: " << mac << "\n\n"; } break;
case 4: { cout << "\nIP Address: " << ipn << "\n\n"; } break;
default: { cout << "\n Cannot return a value. "\n\n"; } break;
} |