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.
复合语句用在语法规则要求使用单个语句但程序逻辑却需要不止一个语句的地方。例如, while 或 for 语句的循环体必须是单个语句。然而,大多数情况都需要在循环体里执行多个语句。因而可使用一对花括号将语句序列括起来,使其成为块语句。
As an example, recall the while loop from our solution to the bookstore problem on page 26:
回顾一下 第 1.6 节处理书店问题的程序,以其中用到的 while 循环为例:
//
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
|
上一页: 第 6.2 节 声明语句 返回上级目录: 第六章 语句 下一页: 第 6.4 节 语句作用域
© 2008 woyouxian.net 版权所有 Contact Us