The Switch Statement
Load and display the file switch.c for an example of the biggest construct yet in the C
language, the switch.
main( )
{
int truck;
for (truck = 3;truck < 13;truck = truck + 1) { switch (truck) { case 3 : printf("The value is three\n"); break; case 4 : printf("The value is four\n"); break; case 5 : case 6 : case 7 : case 8 : printf("The value is between 5 and 8\n"); break; case 11 : printf("The value is eleven\n"); break; default : printf("It is one of the undefined values\n"); break; } /* end of switch */ } /* end of the loop */ } The switch is not difficult, so don’t let it intimidate you. It begins with the keyword "switch" followed by a variable in parentheses which is the switching variable, in this case "truck". As many cases as desired are then enclosed within a pair of braces. The reserved word "case" is used to begin each case entered followed by the value of the variable, then a colon, and the statements to be executed. In this example, if the variable "truck" contains the value 8 during this pass of the switch statement, the printf will cause "The value is three" to be displayed, and the "break" statement will cause us to jump out of the switch. Once an entry point is found, statements will be executed until a "break" is found or until the program drops through the bottom of the switch braces. If the variable has the value 5, the statements will begin executing where "case 5 :" is found, but the first statements found are where the case 8 statements are. These are executed and the break statement in the "case 8" portion will direct the execution out the bottom of the switch. The various case values can be in any order and if a value is not found, the default portion of the switch will be executed. It should be clear that any of the above constructs can be nested within each other or placed in succession, depending on the needs of the particular programming project at hand. Compile and run switch.c to see if it does what you expect it to after this discussion.
0 comments:
Post a Comment