在C/C++中大括号指明了变量的作用域,在大括号内声明的局部变量其作用域自变量声明始,到大括号之后终结。我们应该善用它,使我们的程序更加清晰明白。尤其是在有许多形式重复的代码的程序段中,以下是一个伪代码例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
void MyProcess(MyType input, MyType & output)
{
   MyType filter = input;
   {
      MyType temp;
      step1(filter,temp);
   }
   {
      MyType temp;
      step2(filter,temp);
   }
   {
      MyType temp;
      step3(filter,temp);
   }
   output = filter;
}

以上程序实现了简单的管道/过滤器结构:

         temp1   temp2   temp3
           ↓       ↓       ↓
input → step1 → step2 → step3 → output

temp们都是临时变量,如果没有大括号的约束,每个临时变量都存在于函数作用域中,那么频繁增减流程时出错的概率大大增加了。放在大括号中,不仅程序阅读起来很清楚,而且也不容易出错。

实例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <cstdio>  

int main(int argc, char* argv[])  
{  
    int *pa;  
    {  
        int a=10;  
        pa=&a;  
    }  
    //error C2065: 'a' : undeclared identifier  
    //printf("%d\n",a);  

   /* *pa 的生存期是它所在的栈,所以它的生存期和 main 是一样的。 
    * a的作用域是所在的 block, 也就是它所声明最临近的 {} 之间。 
    * 
    * a在{}外已被销毁,但是a的那块内存还保存有相应数据,在这种小程序中*pa仍可以访问到相应数值,但当程序大到覆盖掉a所在的栈内存时,结果不确定。
        */  
    printf("%d\n",*pa);  
    return 0;  
}

参考:http://blog.csdn.net/zhu2695/article/details/8762965#