Scopes of languages


不同的编程语言可能有不同的作用域,同一语言内也可能存在多种作用域 .

(1) C作用域 有:

  • global scope (known as external linkage)
  • a form of module scope or file scope (known as internal linkage)
  • local scope (within a function)
  • block scope 注意:standard C does not support nested functions.
 #include <stdio.h>
int main(void)
{ 
    char x = 'm';
    printf("%c\n", x);
    {
        printf("%c\n", x);
        char x = 'b';
        printf("%c\n", x);
    }
    printf("%c\n", x);
}

(2) C++作用域 有:

  • 块作用域(局部作用域,for、while、if、switch等语句也构成了块作用域)、
  • 函数作用域
  • 函数原型作用域
  • 全局作用域
  • 文件作用域
  • 命名空间作用域
  • 类作用域(匿名类的作用域)
  • 枚举作用域
// C++语言中多种不同的作用域声明
namespace N { // 命名空间作用域,仅是群组织别名
  class C { // 类作用域,定义/声明成员变量和函数
    void f (bool b) { // 函数作用域,包含可执行语句
      if (b) { // 条件执行语句的无名作用域(块作用域)
      ...
      }
    }
  };
}

(3)java的作用域:

  • 类作用域(Class Level Scope)
  • 函数作用域(Method/Local Level Scope)
  • 块作用域(Block Level Scope)
public class Demostrate { //类级作用域
  public static String hello = "hello";//类级变量
  public float f;//对象级变量
  static { //块级作用域
    ...
  }
  public void foo() { //函数/本地级作用域
  ....
  }
  public static void goo(){ //函数/本地级作用域
    ....
    if() { //块级作用域
      ....
    }
  }
}

(4)javascript的作用域:

  • 全局作用域(Class Level Scope)
  • 函数作用域(Method/Local Level Scope)
  • 块作用域(Block Level Scope)

demo.js


 var a = 1;  // 全局作用域
 var foo = function(){  // 函数作用域
    var name = "xiao";
    var count = 10;

    if (count > 1) {// 块作用域
       var f = "F";
       //.....
    }

    return name;
 }


References

1. C++/作用域

results matching ""

    No results matching ""