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.
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
|