当前位置:嗨网首页>书籍在线阅读

12-复合语句(语句块)

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

5.1.10 复合语句(语句块)

编写C++for语句的格式(或句法)看上去可能比较严格,因为循环体必须是一条语句。如果要在循环体中包含多条语句,这将很不方便。所幸的是,C++提供了避开这种限制的方式,通过这种方式可以在循环体中包含任意多条语句。方法是用两个花括号来构造一条复合语句(代码块)。代码块由一对花括号和它们包含的语句组成,被视为一条语句,从而满足句法的要求。例如,程序清单5.8中的程序使用花括号将3条语句合并为一个代码块。这样,循环体便能够提示用户、读取输入并进行计算。该程序计算用户输入的数字的和,因此有机会使用+=运算符。

程序清单5.8 block.cpp

// block.cpp -- use a block statement
#include <iostream>
int main()
{
    using namespace std;
    cout << "The Amazing Accounto will sum and average ";
    cout << "five numbers for you.\n";
    cout << "Please enter five values:\n";
    double number;
    double sum = 0.0;
    for (int i = 1; i <= 5; i++)
    {                                    // block starts here
        cout << "Value " << i << ": ";
        cin >> number;
        sum += number;
    }                                   // block ends here
    cout << "Five exquisite choices indeed! ";
    cout << "They sum to " << sum << endl;
    cout << "and average to " << sum / 5 << ".\n";
    cout << "The Amazing Accounto bids you adieu!\n";
    return 0;
}

下面是该程序的运行情况:

The Amazing Accounto will sum and average five numbers for you.
Please enter five values:
Value 1: 1942
Value 2: 1948
Value 3: 1957
Value 4: 1974
Value 5: 1980
Five exquisite choices indeed! They sum to 9801
and average to 1960.2.
The Amazing Accounto bids you adieu!

假设对循环体进行了缩进,但省略了花括号:

for (int i = 1; i <= 5; i++)
      cout << "Value " << i << ": ";  // loop ends here
      cin >> number;                     // after the loop
      sum += number;
cout << "Five exquisite choices indeed! ";

编译器将忽略缩进,因此只有第一条语句位于循环中。因此,该循环将只打印出5条提示,而不执行其他操作。循环结束后,程序移到后面几行执行,只读取和计算一个数字。

复合语句还有一种有趣的特性。如果在语句块中定义一个新的变量,则仅当程序执行该语句块中的语句时,该变量才存在。执行完该语句块后,变量将被释放。这表明此变量仅在该语句块中才是可用的:

#include <iostream>
int main()
{
    using namespace std;
    int x = 20;
    {                       // block starts
        int y = 100;
        cout << x << endl;  // ok
        cout << y << endl;  // ok
    }                       // block ends
    cout << x << endl;      // ok
    cout << y << endl;      // invalid, won’t compile
    return 0;

注意,在外部语句块中定义的变量在内部语句块中也是被定义了的。

如果在一个语句块中声明一个变量,而外部语句块中也有一个这种名称的变量,情况将如何呢?在声明位置到内部语句块结束的范围之内,新变量将隐藏旧变量;然后旧变量再次可见,如下例所示:

#include <iostream>
int main()
{
    using std::cout;
    using std::endl;
    int x = 20;              // original x
    {                        // block starts
        cout << x << endl;   // use original x
        int x = 100;         // new x
        cout << x << endl;   // use new x
    }                        // block ends
    cout << x << endl;       // use original x
    return 0;
}