A declaration specifies the interpretation and properties of a set of identifiers. A definition of an
identifier is a declaration for that identifier that for:
— an object, causes storage to be reserved for that object,
— a function, includes the function body,122)
— an enumeration constant, is the first (or only) declaration of the identifier, or
— a typedef name, is the first (or only) declaration of the identifier.
在 C 语言标准中,定义(definition)被视为一种声明(declaration),是由于两者在语义上的关系。下面我们来详细解释一下这个概念。
声明与定义的关系
-
声明的意义:
- 声明的目的是告诉编译器某个标识符(如变量、函数、类型等)是存在的,并且描述该标识符的类型和其他相关属性。
- 声明并不提供存储空间(对于变量)或者函数的实现。
-
定义的意义:
- 定义不仅声明了标识符的名字和类型,而且还为其分配存储空间(变量)或提供实现(函数)。
- 每个定义都至少是一个声明,因为它还需要告知编译器该标识符的类型。
为什么定义也是声明
-
语义层面:任何定义都是语法上有效的声明,因此在某种程度上,所有的定义都可以被视为声明。例如:
int x; // 这是 x 的定义,也是它的声明
在这个例子中,
int x;
不仅声明了x
是一个整数类型,同时也定义了x
。 -
标准的规定:根据 C 语言标准(如 C99 和 C11),定义被视为一种特殊的声明。这意味着当定义一个变量或函数时,编译器会将其视为同时对该标识符进行声明。
例子
-
变量:
int x; // 这是一个定义,也是一个声明 extern int y; // 这是一个声明,但不是定义
-
函数:
int add(int a, int b) { return a + b; // 这是 add 函数的定义,也是声明 } int add(int, int); // 这是一个函数的声明
小结
因此,C 标准将定义视为一种声明,是因为定义在本质上提供了声明的所有功能,并且因为它是构造程序所需的信息的一部分。通过这种方式,编译器能够理解程序的结构,即使这些信息是以定义的方式呈现出来的。