### 6.3. 复合语句（块）

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.

else 分支中，程序逻辑需要输出 total 的值，然后用 trans 重置 total。但是，else 分支只能后接单个语句。于是，用一对花括号将上述两条语句括起来，使其在语法上成为单个语句（复合语句）。这个语句既符合语法规则又满足程序的需要。

 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. 使用逗号操作符（第 5.9 节）重写书店问题中 while 循环里的 else 分支，使它不再需要用块实现。解释一下重写后是提高还是降低了该段代码的可读性。 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? 在解决书店问题的 while 循环中，如果删去 while 后面的左花括号及相应的右花括号，将会给程序带来什么影响？