(原創) c/c++独特的block scope (C/C++)

C/C++的Scope共有6种:global、class、namespace、local、block、statement (C++ Primer 4th P.75) 。其中比较特别的是block scope,只要在curly brace {} 之间,就自成一个scope。

 1#include <iostream>
 2
 3using namespace std;
 4
 5int main() {
 6
 7  int i(1);
 8  cout << i << endl;
 9
10  {
11    int i(2);
12    cout << i << endl;
13  }

14
15  cout << i << endl;
16
17  return 0;
18}

以上的程序在Visual C++ 2005,Turbo C 2.0, Turbo C++ 3.0都可过,执行结果为1 2 1(当然cout要改成prinf()),可见block scope是古早C就有的机制。

但相同的程序代码,若改成C#或Java,连compile都不能过。
C#
 1using System;
 2
 3class HelloWorld {
 4  static void Main(string[] args) {
 5    int i = 1;
 6    Console.WriteLine(i);
 7
 8    {
 9      int i = 2;
10      Console.WriteLine(i);
11    }

12
13    Console.WriteLine(i);
14  }

15}

16

C# compile会出现以下错误讯息

A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'parent or current' scope to denote something else 

Java

 1public class HelloWorld {
 2    
 3  public static void main(String[] args) {
 4    int i = 1;
 5    System.out.println(i);
 6        
 7    {
 8      int i = 2;
 9      System.out.println(i);
10    }

11        
12    System.out.println(i);
13  }
    
14}

15

Java compile会出现以下错误讯息
Duplicate local variable i

 很显然C#和Java都没有block scope的概念。

block scope有什么用呢?

举例来说,本来在程序中只连上SQL Server,故将此Connection命名为con,但后来修改程序,还要连上Oracle,因为con变量已经用过了,可能得另取con1为变量名,或取conOracle,但这样的命名规则就和之前的程序不同,造成整个程序风格不一,若有block scope,则不用在对变数命名有任何困扰,SQL Server区段,用{}包起来,使用con为变量名称,Oracle区段,也用{}包起来,继续使用con为变量名称,因为彼此不相干扰,所以可以用相同的变量名称。

或许有人会说,这样的程序风格,以后不好debug吧,假如在{}外也宣告con,这样类似global variable和local variable相同,的确难以debug,但若con都写在{}内,则都是local variable,且step by step debug时,local window只要出了{},该变数就会不见,类似function中又有小function,我记得在Pascal语言中,就有Procedure内中又有Procedure的写法,所以应该不难debug,不过,既然C#和Java这两个modern language都不支持block scope,或许这种写法真的不好维护,且我在其它C/C++的书上,也没看过这种写法。我会用这种写法一段时间实验看看,看是否真的不好维护,有任何心得我会继续报告。


Reference 
C++ Primer 4th P.54 ~ P.55 P.75 

posted on 2006-10-08 12:18  真 OO无双  阅读(1802)  评论(0编辑  收藏  举报

导航