Section 6.4. Selection Statements


6.4. Selection Statements

A selection statement can direct the flow of program execution along different paths depending on a given condition. There are two selection statements in C: if and switch.

6.4.1. if Statements

An if statement has the following form:

 if ( expression ) statement1 [ else statement2 ] 

The else clause is optional. The expression is evaluated first, to determine which of the two statements is executed. This expression must have a scalar type. If its value is TRuethat is, not equal to 0then statement1 is executed. Otherwise, statement2, if present, is executed.

The following example uses if in a recursive function to test for the condition that ends its recursion:

 // The recursive function power( ) calculates // integer powers of floating-point numbers. // ----------------------------------------- double power( double base, unsigned int exp ) {    if ( exp == 0 ) return 1.0;    else return base * power( base, exp-1 ); } 

If several if statements are nested, then an else clause always belongs to the last if (on the same block nesting level) that does not yet have an else clause:

 if ( n > 0 )    if ( n % 2 == 0 )       puts( "n is positive and even" );    else                                 // This is the alternative       puts( "n is positive and odd" );  // to the last if 

An else clause can be assigned to a different if by enclosing the last if statement that should not have an else clause in a block:

 if ( n > 0 ) {   if ( n % 2 == 0 )      puts( "n is positive and even" ); } else                                  // This is the alternative    puts( "n is negative or zero" );   // to the first if 

To select one of more than two alternative statements, if statements can be cascaded in an else if chain. Each new if statement is simply nested in the else clause of the preceding if statement:

 // Test measurements for tolerance. // -------------------------------- double spec = 10.0, measured = 10.3, diff; /* ... */ diff = measured - spec; if ( diff >= 0.0 && diff < 0.5 )    printf( "Upward deviation: %.2f\n", diff ); else if ( diff < 0.0 && diff > -0.5 )    printf( "Downward deviation: %.2f\n", diff ); else    printf( "Deviation out of tolerance!\n" ); 

The if conditions are evaluated one after another. As soon as one of these expression yields TRue, the corresponding statement is executed. Because the rest of the else if chain is cascaded under the corresponding else clause, it is alternative to the statement executed, and hence skipped over. If none of the if conditions is true, then the last if statement's else clause is executed, if present.

6.4.2. switch Statements

A switch statement causes the flow of program execution to jump to one of several statements according to the value of an integer expression:

 switch ( expression ) statement 

expression has an integer type, and statement is the switch body, which contains case labels and at most one default label. The expression is evaluated once and compared with constant expressions in the case labels. If the value of the expression matches one of the case constants, the program flow jumps to the statement following that case label. If none of the case constants matches, the program continues at the default label, if there is one.

Example 6-6 uses a switch statement to process the user's selection from a menu.

Example 6-6. A switch statement
 // Handle a command that the user selects from a menu. // --------------------------------------------------- // Declare other functions used: int menu( void );              // Prints the menu and returns                                // a character that the user types. void action1( void ),      action2( void ); /* ... */ switch ( menu( ) )              // Jump depending on the result of menu( ). {    case 'a':    case 'A':  action1( );       // Carry out action 1.               break;           // Don't do any other "actions."    case 'b':    case 'B':  action2( );       // Carry out action 2.               break;           // Don't do the default "action."    default:   putchar( '\a' ); // If no recognized command, }                              // output an alert. 

The syntax of the case and default labels is as follows:

 case constant:   statement default:         statement 

constant is a constant expression with an integer type. Each case constant in a given switch statement must have a unique value. Any of the alternative statements may be indicated by more than one case label, though.

The default label is optional, and can be placed at any position in the switch body. If there is no default label, and the control expression of the switch statement does not match any of the case constants, then none of the statements in the body of the switch statement is executed. In this case, the program flow continues with the statement following the switch body.

The switch body is usually a block statement that begins with a case label. A statement placed before the first case label in the block would never be executed.

Labels in C merely identify potential destinations for jumps in the program flow. By themselves, they have no effect on the program. Thus, after the jump from the switch to the first matching case label, program execution continues sequentially, regardless of other labels. If the statements following subsequent case labels are to be skipped over, then the last statement to be executed must be followed by a break statement. The program flow then jumps to the end of the switch body.

If variables are declared within a switch statement, they should be enclosed in a nested block:

 switch ( x ) {    case C1: {  int temp = 10;     // Declare temp only for this "case"                /* ... */             }             break;    case C2:             /* ... */ } 

Integer promotion is applied to the switch expression. The case constants are then converted to match the resulting type of the switch expression.

You can always program a selection among alternative statements using an else if chain. If the selection depends on the value of one integer expression, however, then you can use a switch statementand should, because it makes code more readable.



C(c) In a Nutshell
C in a Nutshell (In a Nutshell (OReilly))
ISBN: 0596006977
EAN: 2147483647
Year: 2006
Pages: 473

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net