1. | Welcome | ToC | FAQ | Resources | Courses | Projects | Mail Lists | Members | Misc |
2. | Fundamentals | Languages | Tools | Net | Core | Advanced |
3. | EoC | Java |
4. | Lessons |
5. | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 |


Essence of C
3 - PROGRAM CONTROL STATEMENTS

Conditional, Iteration, and Jump Statements

Overview

The ANSI standard categorizes C's program control statements as follows:

Category Relevant Keywords
Selection (or Conditional) Statements if switch
Iteration for while do-while
Jump break goto return continue
Label case default

True and False and Conditional Expressions in C

Many C statements rely on the outcome of a conditional expression which evaluates to either true or false. In C, unlike many other languages, true is any non-zero value and false is zero. This approach facilitates efficient coding.

The programmer is not restricted to conditional expressions involving only the relational and logical operators (as in BASIC or Pascal). Any valid C expression may be used to control the if. All that is required is an evaluation to either zero or no-zero. For example:

     b = a * c;


     if(b)
       printf(&quot%d\n&quot,b);
     else
       printf("b evaluated to zero\n&quot);

Selection (or Conditional) Statements

The if Statement

The general form of an if statement is:

     if(expression)
       statement;
     else
       statement;

where statement may be a single statement, a block, or nothing, and the else statement is optional. The conditional statement produces a scalar result, ie, an integer, character or floating point type.

Nested ifs. The ANSI standard specifies that 15 levels of nesting must be supported. In C, an else statement always refers to the nearest if statement in the same block and not already associated with an if. For example:

     if(i)
     {
       if(j)
         statement 1;
       if(k)                     // this if is associated with
         statement 2;
       else                      // this else
         statement 3;
     }
     else                        // this is associated with if(i)
       statement 4;

The if-else-if Ladder. To avoid excessive indentation, if-else-if ladders are normally written like this:

     if(expression)
       statement;
     else if(expression)
       statement;
     else if(expression)
       statement;
     ...
     else
       statement;


The switch Statement

switch successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed. The general form is:

     switch(expression)
     {
       case constant1:
         statement sequence;
         break;

      case constant2:
         statement sequence;
         break;
      ...

       default:
         statement sequence;
     }

default: is executed if no matches are found.

Although case is a label statement, it cannot exist outside a switch.

Some important aspects of switch are as follows:

If the break statement is omitted, execution continues on into the next case statement until either a break or the end of the switch is reached. For example, in:

     switch(i)
     {
       case 1:
       case 2:
       case 3:
         flag=0;
         break;

       case 4:
        flag=1;

       case 5:
         error(flag);
         break;

       default:
         process(ch);
     }

if i is equal to either 1, 2 or 3, flag is set to 0. If i is equal to 4, flag is set to 1 and error(flag) is executed. If i is equal to 5, error(flag) is called with whatever value was in flag before the switch was entered.

Nested switch Statements. A switch statement may be part of the statement sequence of an outer switch.

Iteration Statements

The for Loop

The general form of the for statement is:

     for(initialization;condition;increment)
       statement;

initialization is generally an assignment statement used to set the loop control variable. condition is a relational expression that determines when the loop exits. increment defines how the loop variable changes each time the loop is repeated.

In for loops, the conditional test is always performed at the top of the loop, which means that the code inside the loop may not be executed at all if the condition is false to begin with, as in:

     x = 10;
     for(y=10;y!=x;++y)
       printf(&quot%d&quot,y);

Variation 1 - The Comma Operator. A variant of the for loop is made possible by the comma operator, as in:

     for(x=0,y=0;x+y<10;++x);

in which both x and y control the loop.

Variation 2 - Missing Pieces of the Loop Definition. An interesting trait of the for loop is that pieces of the loop definition need not be there. For example, in:

     for(x=0;x!=123; )
       scanf("%d",&x);

each time the loop repeats, x is tested to see if it equals 123. The loop condition only becomes false, terminating the loop, when 123 is entered.

Variation 3 - The Infinite Loop. If all of the pieces in the loop definition are missing, an infinite loop is created. However, the break statement may be used to break out of the loop, as in:

     for(;;)
     {
       ch = getchar();
       if(ch == 'A')
         break;
     }

Variation 4 - for Loops With No Bodies. The body of the for loop may also be empty. This improves the efficiency of some code. For example, the following removes leading spaces from the stream pointed to by str:

     for( ;*str==' ';str++) ;

Time delay loops are another application of a loop with an empty body, eg:

     for(t=0;t<1000;t++);


The while Loop

The general form of the while loop is:

     while(condition)
       statement;

where statement is either an empty statement, a single statement or a block of statements. The loop iterates while the condition, which is executed at the top of the loop, is true.

Variation 1 - No Body. The following, which is an example of a while loop with no body, loops until the user types A:

     while((ch=getchar()) !='A') ;


The do-while Loop

The do-while loop tests the condition at the bottom of the loop rather than at the top. This ensures that the loop will always execute at least once. In the following example, the loop will read numbers from the keyboard until it finds a number equal to or less than 100:

     do
     {
       scanf("%d",&num);
     } while num>100;

Jump Statements

The return Statement

The return statement is used to return from a function. If return has a value associated with it, that value is returned by the function. If no return value is specified, either zero or a garbage value will be returned, depending on the compiler. The general form of the return statement is:

     return expression;

The } which ends a function also causes the function to return. A function declared as void may not contain a return statement that specifies a value


The goto Statement

The goto statement requires a label (an identifier followed by a colon), which must be in the same function as the goto.


The break Statement

The break statement has two uses:


The exit() Function

The standard library function exit() causes immediate termination of the entire program. The general form of the exit function is:

     void exit(int return_code);

The value of return_code is returned to the operating system. Zero is generally used as a return code to indicate normal program termination. Other arguments are used to indicate some sort of error.


The continue Statement

The continue statement forces the next iteration of the loop, skipping any code in between. For the for loop, continue causes the conditional test and then the increment portion of the loop to execute. For the while and do-while loops, program control passes to the conditional test.

Prior Chapter · Index · Next Chapter


Copyright © 1996, 1997, 1998. Last Update to This Page: 1998/10/24
This Page Maintained by: radar pangaean * * * Original Author: K.J.Bricknell
The MOST web site is built and maintained by the voluntary efforts/donations of our members.