Chapter 5 *Flow Control

Table of Contents
5.1 Compound Statements
5.2 If
5.3 Switch
5.4 Break and Continue
5.5 While
5.6 Do-while
5.7 For
5.8 Goto
Written by Francesco Marletta. Marked up by Dave Chapeskie. Additional writing by Markus Delves.

Note: This chapter is a work in process. Contact Francesco Marletta or Markus T. Delves with comments.

Until now we have seen only sequential code, that is, piece of programs that are executed one instruction after the other, from the first to the last. But when you write programs that manipulate user provided data, as well as recorded data, you may want choose between some exclusive code sequence, or repeat some instructions over and over. Flow control gives you the ability of change the order in which the program statements will be executed. So if you want to create 100 payroll checks you don't need to write the same code 100 times, but only once and than repeat it 100 times, with the advantage that if the number of the payroll checks grows, you don't need to rewrite the program to increase the number of times the loop is executed if this number is outside data!

5.1 Compound Statements

Everytime we need to group multiple statements, we must use a compound statement. Sometimes, compound statements are also called a block.

The syntax of a compound statement:

    {
        /* declarations */
    
        /* statement list */
    }

It starts with zero or more declarations, followed by zero or more statements. Compound statements can be used wherever you would normally have one statement. It can be use to denote your code, control the scope of a variable, etc. They are usefull with most of the flow control operators. Of course, they execute the statements in a linear fashion.

For example, here is a compound statement used as the conditional part of an if:

    if (b < a) {
        double tmp;
    
        /* swap `a' and `b' */
        tmp = a;
        a = b;
        b = tmp;
    }

It's important to remember that a compound statement is a statement itself, and can be use anywhere a statement could have been use.

This, and other documents, can be downloaded from http://opencbp.sourceforge.net/.

For questions about the Open C Book Project, read the documentation.