I l @ ve RuBoard |
The keyword for the switch statement is switch .
Program control jumps to the statement bearing the value of expression as a label. Program flow then proceeds through the remaining statements unless redirected again. Both expression and labels must have integer values (type char is included), and the labels must be constants or expressions formed solely from constants. If no label matches the expression value, control goes to the statement labeled default , if present. Otherwise, control passes to the next statement following the switch statement. After control goes to a particular label, all the subsequent statements in the switch are executed until the end of the switch , or a break statement, is encountered , whichever comes first.
switch ( expression ) { case label1 : statement1 case label2 : statement2 default : statement3 }
There can be more than two labeled statements, and the default case is optional.
switch (value) case 1 : find_sum(ar, n); break; case 2 : show_array(ar, n); break; case 3 : puts("Goodbye!"); break; default : puts("Invalid choice, try again."); break; } switch (letter) { case `a' : case `e' : printf("%d is a vowel\n", letter); case `c' : case `n' : printf("%d is in \"cane\"\n", letter); default : printf("Have a nice day.\n"); }
If letter has the value 'a' or 'e' , all three messages are printed; 'c' and 'n' cause the last two to be printed. Other values print only the last message.
I l @ ve RuBoard |