「C」- Scope, Linkage, Storage Duration, Storage Class

问题描述

该笔记是《C Primer Plus, 中文版, 第 6 版》/ 第 12 章 存储类别、链接和内存管理(Page 373)的学习笔记。

Scope

Scope,作用域:定义变量的作用范围;

Block Scope

Block Scope,块作用域:
1)该类型的作用域是 从定义处开始包含该定义的块的末尾
2)另外,虽然形式参数声明在函数的左花括号({)之前,但是它们也是块作用域;

形态:

double blocky(double cleo) {
    double patrick = 0.0;      // 仅当前块内能够访问,且仅在该声明之后
    ...
    return patrick;
}

Function Scope

Function Scope,函数作用域:
1)仅用于 goto 语句的标签,即:对于在函数内的标签,其作用域直接延伸到整个函数;

形态:

int main() {

   for (i = 1; i <= 5; ++i) {
      if (i > 4)
         goto jump;
   }

jump:                          // 该函数的任何位置都能访问该
   printf("end");
   return 0;
}

Function Prototype Scope

Function Prototype Scope,函数原型作用域:
1)该类型的作用域是 从形参定义处原型声明结束

File Scope

File Scope,文件作用域:
1)该类型的作用域是 从定义开始文件末尾 均可见;

Linkage

Linkage(链接)是对 File Scope 的进一步定义,分为:

External Linkage

External Linkage(外部链接):能够在多文件程序中使用,即能够被其他源文件引用;

Internal Linkage

Internal Linkage(内部链接):仅在当前 Translation Unit 内部可见(当前文件可见);

No Linkage

No Linkage(无链接):即仅能块内部使用;例如 Function Scope、Block Scope 等等都属于 No Linkage 类型;

Storage Duration

Storage Duration(存储期),描述被访问对象(变量)的生存期,分为

Static Storage Duration

Static Storage Duration,静态存储期:
1)该类型的变量,在程序执行期间,持续存在;

Thread Storage Duration

Thread Storage Duration,线程存储期:
1)该类型的变量,从声明开始,到线程结束,持续存在;

Automatic Storage Duration

Automatic Storage Duration,自动存储期:
1)自动创建,自动释放,例如 Block Scope 类型的变量通常都为自动存储期;

Allocated Storage Duration

Allocated Storage Duration,自动分配存储期:
1)WIP

Storage Class

Storage Classs(存储类别):通过 Scope / Linkage / Storage Duration 组合,以得到变量的多种存储方案。

Storage ClassStorage DurationScopeLinkageDescription
Automatic,自动AutomaticBlockNo在块内声明
Register,寄存器AutomaticBlockNo在块内声明,使用 register 关键字
Static with External LinkageStaticFileExternal在函数外声明
Static with Internal LinkageStaticFileInternal在函数外声明,使用 static 关键字
Static with No LinkageStaticBlockNo在块内声明,使用 static 关键字