Tru64 UNIX
Compaq C Language Reference Manual


Previous Contents Index

7.5.2 The switch Statement

The switch statement executes one or more of a series of cases, based on the value of a controlling expression. The switch statement has the following syntax:

switch ( expression )
statement

The usual arithmetic conversions are performed on the control expression, but the result must have an integral type. For more information about data-type conversion, see Section 6.11. The switch statement is typically a compound statement, within which are one or more case statements executed if the control expression matches the case . The syntax for a case label and expression follows:

case constant-expression : statement

The constant expression must have an integral type. No two case labels can specify the same value. There is no limit on the number of case labels in a switch statement.

Only one statement in the compound statement can have the following label:

default :

The case and default labels can occur in any order, but it is common practice for the default statement to follow the case statements. Note that execution flows from the selected case into the cases following unless explicit action is taken, such as a break statement.

When the switch statement is executed, the following sequence takes place:

  1. The switch control expression is evaluated (and integral promotions applied) and compared with the constant expressions in the case labels.
  2. If the control expression's value matches a case label, control transfers to the statement following that label. If a break statement is encountered, the switch statement terminates; otherwise, execution continues into the following case or default statements until a break statement or the end of the switch statement is encountered (see Example 7-1).
    A switch statement can also be terminated by a return or goto statement. If a switch statement is inside a loop, the switch statement is terminated if a continue statement terminates the loop. See Section 7.7 for more information about these statements.
  3. If the control expression's value does not match any case label, and there is a default label, control is transferred to the statement following that label. If a break statement does not end the default statement, and a case label follows, that case statement is executed.
  4. If the control expression's value does not match any case label and there is no default label, execution of the switch statement terminates.

Example 7-1 uses the switch statement to count blanks, tabs, and new-line characters entered from the terminal.

Example 7-1 Using switch to Count Blanks, Tabs, and New Lines

/*  This program counts blanks, tabs, and new lines in text * 
 *  entered from the keyboard.                              */ 
 
 
#include <stdio.h> 
main() 
{ 
   int number_tabs = 0, number_lines = 0, number_blanks = 0; 
   int ch; 
   while ((ch = getchar()) != EOF) 
      switch (ch) 
         { 
(1)            case '\t':  ++number_tabs; 
(2)                        break; 
            case '\n':  ++number_lines; 
                        break; 
            case ' ' :  ++number_blanks; 
                        break; 
            default:; 
         } 
   printf("Blanks\tTabs\tNewlines\n"); 
   printf("%6d\t%6d\t%6d\n", number_blanks, 
                             number_tabs,number_lines); 
} 

Key to Example 7-1:

  1. A series of case statements is used to increment separate counters depending on the character encountered.
  2. The break statement causes control to return to the while loop. Control is passed to the while loop if the value of ch does not match any of the case constant expressions.

Without the break statements, each case would drop through to the next.

If variable declarations appear in the compound statement within a switch statement, initializers on auto or register declarations are ineffective. However, initializations within the statements following a case are effective. Consider the following example:


switch (ch) 
   { 
      int nx = 1;          /* Initialization ignored            */ 
      printf("%d", n);     /* This first printf is not executed */ 
      case 'a' : 
       { int n = 5;        /* Proper initialization occurs      */ 
         printf("%d", n); 
         break; } 
      case 'b' : 
         { break; } 
      default : 
         { break; } 
   } 

In this example, if ch == 'a' , then the program prints the value 5. If the variable equals any other letter, the program prints nothing because the initialization occurs outside of the case label, and statements outside of the case label are ineffective.

7.6 Iteration Statements

An iteration statement, or loop, repeatedly executes a statement, known as the loop body, until the controlling expression is false (0). The control expression must have a scalar type.

The while statement evaluates the control expression before executing the loop body (see Section 7.6.1).

The do statement evaluates the control expression after executing the loop body; at least one execution of the loop body is guaranteed (see Section 7.6.2).

The for statement executes the loop body based on the evaluation of the second of three expressions (see Section 7.6.3).

7.6.1 The while Statement

The while statement evaluates a control expression before each execution of the loop body. If the control expression is true (nonzero), the loop body is executed. If the control expression is false (0), the while statement terminates. The while statement has the following syntax:

while ( expression )
statement

Consider the following while statement:


n = 0; 
while (n < 10) 
   { 
      a[n] = n; 
      n++; 
   } 

This statement tests the value of n ; if n is less than 10, it assigns n to the nth element of the array a and then increments n . The control expression (in parentheses) is then evaluated; if true (nonzero), the loop body is executed again; if false (0), the while statement terminates. If the statement n++ were missing from the loop body, this while statement would never terminate. If the statement n = 0 were replaced by the statement n = 10 , the control expression is initially false (0), and the loop body is never executed.

7.6.2 The do Statement

The do statement evaluates the control expression after each execution of the loop body. The do statement has the following syntax:

do
statement
while ( expression ) ;

The loop body is executed at least once. The control expression is evaluated after each execution of the loop body. If the control expression is true (nonzero), the statement is executed again. If the control expression is false (0), the do statement terminates.

7.6.3 The for Statement

The for statement evaluates three expressions and executes the loop body until the second controlling expression evaluates to false (0). The for statement is useful for executing a loop body a specified number of times. The for statement has the following syntax:

for ( expression-1opt ;
expression-2opt ; expression-3opt)
statement

The for statement is equivalent to the following code:

expression-1;


while ( expression-2 )
{
statement
expression-3 ;
}

The for statement executes the loop body zero or more times. Semicolons (;) are used to separate the control expressions. A for statement executes the following steps:

  1. expression-1 is evaluated once before the first iteration of the loop. This expression usually specifies the initial values for variables used in the loop.
  2. expression-2 is any scalar expression that determines whether to terminate the loop. expression-2 is evaluated before each loop iteration. If the expression is true (nonzero), the loop body is executed. If the expression is false (0), execution of the for statement terminates.
  3. expression-3 is evaluated after each iteration.
  4. The for statement executes until expression-2 is false (0), or until a jump statement, such as break or goto , terminates execution of the loop.

Any of the three expressions in a for loop can be omitted:

In relaxed ANSI C mode, the first clause of the for statement can be a declaration whose scope includes the remaining clauses of the for header and the entire loop body. This is normally used to declare and initialize a local loop control variable. For example:


for (int i=0; i<10; i++) 
    printf("%d\n", i); 

7.7 Jump Statements

Jump statements cause an unconditional jump to another statement elsewhere in the code. They are used primarily to interrupt switch statements and loops.

The jump statements are the goto statement, the continue statement, the break statement, and the return statement, which are discussed in the following sections.

7.7.1 The goto Statement

The goto statement unconditionally transfers program control to a labeled statement, where the label identifier is in the scope of the function containing the goto statement. The labeled statement is the next statement executed. The goto statement has the following syntax:

goto identifier;

Care must be taken when branching into a block by using the goto statement, because storage is allocated for automatic variables declared within a block when the block is activated. When a goto statement branches into a block, automatic variables declared in the block are not initialized.

7.7.2 The continue Statement

The continue statement passes control to the end of the immediately enclosing while , do , or for statement. The continue statement has the following syntax:

continue;

The continue statement is equivalent to a goto statement within an iteration statement that passes control to the end of the loop body. For example, the following two loops are equivalent:


while(1)                           while(1) 
{                                  { 
   .                                  . 
   .                                  . 
   .                                  . 
  goto label_1;                     continue; 
   .                                  . 
   .                                  . 
   .                                  . 
  label_1:                        
   ;                                  ; 
 }                                  } 

The continue statement can be used only in loops. A continue inside a switch statement that is inside a loop causes continued execution of the enclosing loop after exiting from the body of the switch statement.

7.7.3 The break Statement

The break statement terminates execution of the immediately enclosing while , do , for , or switch statement. Control passes to the statement following the loop body (or the compound statement of a switch statement). The break statement has the following syntax:

break;

See Example 7-1 which uses a break statement within a switch statement.

7.7.4 The return Statement

The return statement terminates execution of a function and returns control to the calling function, with or without a return value. A function may contain any number of return statements. The return statement has the following syntax:

return expressionopt;

If present, the expression is evaluated and its value is returned to the calling function. If necessary, its value is converted to the declared type of the containing function's return value.

A return statement with an expression cannot appear in a function whose return type is void . For more information about the void data type and function return types, see Sections 3.5 and 3.4.1.

If there is no expression and the function is not defined as void , the return value is undefined. For example, the following main function returns an unpredictable value to the operating system:


main ( ) 
  { 
   return; 
  } 

Reaching the closing brace that terminates a function is equivalent to executing a return statement without an expression.


Previous Next Contents Index