O'Reilly logo

Beginning Mac OS® X Programming by Drew McCormack, Michael Trent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.6. Conditional Branching

In the previous section, you became acquainted with conditional branching, whether you realized it or not. Branching occurs in a program when execution can jump to different parts of the code depending on the situation. The term branching refers to the way that program execution can follow different paths, like a monkey climbing a tree, or someone rowing up a river. In the case of the if/else construction, the program chooses between jumping to the block of code just after the if statement, or to the block of code after the else statement. The path followed depends on whether the condition in parentheses is true or false. This explains the "conditional" in "conditional branching": the branch followed depends on whether a condition is true or false.

Consider the following if/else construct:

if ( everestIsHigh ) {
    printf("Everest is apparently a high mountain");
}
else {
    printf("Which world do you originate from?");
}

This is the same form of if/else used in the previous example. If the value in parentheses, everestIsHigh, evaluates to a non-zero value, the code in the if block will be evaluated; otherwise, the code in the else block is evaluated. Each code block is enclosed in braces, and may consist of zero or more statements. The placement of the braces is entirely at your discretion, because C ignores extra white space, including new lines. The following rewriting of the example is also perfectly legal, but not advisable:

if ( everestIsHigh ) { printf("Everest ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required