c语言中标识符的作用域

1、代码块作用域(block scope

位于一对花括号之间的所有语句称为一个代码块,在代码块的开始位置声明的标识符具有代码块作用域,表示它们可以被这个代码中的所有语句访问。函数定义的形式参数在函数体内部也具有代码块作用域。当代码块处于嵌套状态时,如果内层代码块有一个标识符与外层代码块的标识符同名,则内层的标识符将屏蔽外层的标识符,也就是外层的标识符无法在内层代码块中通过名字访问。如运行以下代码:

int a(int b){

    printf("外层的b:%d\n",b);

    {

        int b=3;

        printf("内层的b:%d\n",b);

    }

}

int main(){

    a(2);

    system("pause");

    return 0;

}

 

得到的结果就是

外层的b:2

内层的b:3

2、文件作用域(file scope

任何在代码块之外的标识符都具有文件作用域,它表示这些标识符从声明之处开始到它所有的源文件结尾处都是可以被访问的。在头文件中编写并通过#include指令包含到其他文件中的声明就好像它们是直接写在那些文件中一样,它们的作用域并不局限于头文件的文件尾。

3、原型作用域(prototype scope

原型作用域只适用于在函数原型中声明的参数名如:

int a(int b);//这是一个函数原型声明

在上面的函数原型声明中,参数b的名字并非必需,但是如果出现参数名,可以随便取,可以不跟函数定义中的形参名匹配,也不必与函数实际调用时传递的实参匹配。原型作用域防止这些参数名与程序其他部分的名字冲突。

4、函数作用域(function scope 

The only type of identifier with function scope is a label name. A label is implicitly declared by its appearance in the program text and is visible throughout the function that declares it.

A label can be used in a goto statement before the actual label is seen.

可见唯一有函数作用域的标识符类型是标签名称(label name),什么是标签呢,The label consists of the identifier and the colon (:) character. 类似于下面这样的就是了:

identifier:statement

case:1

default:

goto:statement

A label name must be unique within the function in which it appears. 

函数中出现的标签名称必须唯一。

posted on 2015-12-30 16:08  acodewarrior  阅读(1153)  评论(0编辑  收藏  举报

导航