Section 6.3. Compound Statements (Blocks)


6.3. Compound Statements (Blocks)

A compound statement, usually referred to as a block, is a (possibly empty) sequence of statements surrounded by a pair of curly braces. A block is a scope. Names introduced within a block are accessible only from within that block or from blocks nested inside the block. As usual, a name is visible only from its point of definition until the end of the enclosing block.

Compound statements can be used where the rules of the language require a single statement, but the logic of our program needs to execute more than one. For example, the body of a while or for loop must be a single statement. Yet, we often need to execute more than one statement in the body of a loop. We can do so by enclosing the statements in a pair of braces, thus turning the sequence of statements into a block.

As an example, recall the while loop from our solution to the bookstore problem on page 26:

      // if so, read the transaction records      while (std::cin >> trans)          if (total.same_isbn(trans))              // match: update the running total              total = total + trans;         else {              // no match: print & assign to total              std::cout << total << std::endl;              total = trans;      } 

In the else branch, the logic of our program requires that we print total and then reset it from TRans. An else may be followed by only a single statement. By enclosing both statements in curly braces, we transform them into a single (com-pound) statement. This statement satisfies the rules of the language and the needs of our program.

Unlike most other statements, a block is not terminated by a semicolon.



Just as there is a null statement, we also can define an empty block. We do so by using a pair of curlies with no statements:

      while (cin >> s && s != sought)          { } // empty block 

Exercises Section 6.3

Exercise 6.1:

What is a null statement? Give an example of when you might use a null statement.

Exercise 6.2:

What is a block? Give an example of when you might use a block.

Exercise 6.3:

Use the comma operator (Section 5.9, p. 168) to rewrite the else branch in the while loop from the bookstore problem so that it no longer requires a block. Explain whether this rewrite improves or diminishes the readability of this code.

Exercise 6.4:

In the while loop that solved the bookstore problem, what effect, if any, would removing the curly brace following the while and its corresponding close curly have on the program?




C++ Primer
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2006
Pages: 223
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net