اینجا هستید : safarionline.ir / books / cpl / ch03

ch03 - Control Flow

🔵 The control-flow statements of a language specify the order in which computations are performed.

🔵 An expression such as x = 0 or printf(...) becomes a stetment when it is followed by a semicolon, as in

x = 0;
i++;
printf(...);

📝 In C, the semicolon is a statement terminator, rather than a seperator as it is in languages like Pascal.

🔵 Braces { and } are used to group declarations and statements together into a compound statement, or block, so that they are syntactically equivalent to single statement. The braces that surround the statements of a function are one obvious example; braces around multiple statements after if, else, while, or for are another.

🔵 Variables can be declared inside any block; we will talk about this in Chapter 4.

🔵 There is no semicolon after the right brace that ends a block.

⚪ The if-else statement is used to express decisions. Formally, the syntax is

if (expression)
    statement1
else
    statement2

where the else part is optional.

🔵 Since an if simply tests the numeric value of an expression, certain coding shortcuts are possible. The most obvious is writing

if (expression)

/* instead of */

if (expression != 0)

Sometimes this is natural and clear; at other times it can be cryptic.

🔵 Because the else part of an if-else is optional, there is an ambiguity when an else is omitted from a nested if sequence. This is resolved by associating the else with the closest previous else-less if. For example, in:

if (n > 0)
    if (a > b)
        z = a;
    else
        z = b;

the else goes with the inner if, as we have shown by indentation. If that isn't what you want, braces must be used to force the proper association:

if (n > 0) {
    if (a > b)
        z = a;
}
else
    z = b;

🔔 The ambiguity is especially pernicious in situations like this:

if (n >= 0)
    for (i = 0; i < n; i++)
        if (s[i] > 0) {
            printf("...");
            return i;
        }
else        /* WRONG */
    printf("error -- n is negative\n");

The indentation shows unequivocally what you want, but the compiler doesn't get the message, and associates the else with the inner if. This kind of bug can be hard to find; it's a good idea to use braces when there are nested ifs.

© کلیه‌ی حقوق برای safarionline.ir محفوظ است.