Cloudbook: C

  1. Home
  2. Control ← prevnext →
Control

C is an imperative and block-structure language. The natural unit of action is a statement, and statements are followed in order unless a branching command will affect the control flow. Statements can be collected into blocks, and the block determines a higher unity of action, delimiting variable scopes and lifetimes.

A predicate is an expression whose values are considered to be either true or false. Traditionally, C has mapped types to true or false by mapping the zero value to false, and all other values to true. A predicate can make a judgement on the state of the world, and code flow can be altered based on that judgement.

Branching statements precondition the running of a block on the truth of a predicate. If a statement or block is S, and the predicate P, the general formula is: if (P) S, and often an alternative version: if (P) S else S', to specify that either S or S' will run, but never both, depending on the outcome of evaluating P.

Looping statements repeat the run of a block until a predicate yields the desired truth. The while statement is: while (P) S, which repeats S until P evaluates false.

The provision of a number of control statements is a convenience to the programmer. It is certainly true that the looping control statements introduce something new to the ability of code. Without loops, it is impossible to write a program which runs for an arbitrarily long period of time. Without loops, the finite number of statements in a program are consumed at some rate, and will eventually all be consumed, and the program finished. With loops, a program might continue indefinitely.

Therefore some looping construct must be provided; but given almost any looping construct, all others can be constructed. Given the while loop, even if-else structures can be constructed, as well as the do-while loop, and the for loop.

For instance, if S is a statement or block, and P a predicate, than if (P) S is equivalent to:

        { flag = 1 ; while ( flag && P ) { S; flag = 0 ; }}
        
A do-while and for loop are also forms of while loops, with the equivalence shown by using similar constructs that use the while loop construct to exactly implement the behavior of other constructs.
Copyright 2015, 2017 Burt Rosenberg. All Rights Reserved.