Next: , Up: Expressions And Statements   [Index]

6.1 The If Statement

The statement provides for conditional execution of code. In its simplest form a block is executed if the previously tested and coded condition passes.

    if (a == 7) {
	o_text("a is 7\n");

The condition is the computed value of the expression enclosed by parantheses and immediately following the ‘if’ keyword passing the non zero test. If the condition passes, i.e. the expression value is not zero, the block is executed. If it doesn’t the program execution continues with the first instruction after the block.

The test expression should evaluate to one of the numerical intrinsic types.

The basic form of the ‘if’ statement may be augumented by an ‘else’ clause, introducing a block to execute when the condition fails.

    if (a % 2) {
	o_text("a is odd\n");
    } else {
	o_text("a is even\n");

The fragment will print odd when a has values like 1, 3, 11, 1107, and even when a has values like 0, 2, 65536.

Any number of ‘elif’ clauses may appear after the ‘if’ clause and before a final ‘else’ clause, introducing blocks to be executed for ancillary conditions passing.

    if (index("aeiou", c) != -1) {
	o_text("c is a vowel\n");
    } elif (index("bcdfghjklmnpqrstvwxyz", c) != -1) {
	o_text("c is a consonant\n");
    } elif (index("0123456789", c) != -1) {
	o_text("c is a digit\n");
    } else {
	o_text("I don't know what c is\n");
    if (c == 'a') {
    } elif (c == 'e') {
    } elif (c == 'i') {
    } elif (c == 'o') {
    } elif (c == 'u') {

The above ‘if’ statement has no effect, but it tests thoroughly for every vowel.