C语言中定义与声明的本质区别:有无内存分配

来源:互联网 发布:易辅客栈模块源码 编辑:程序博客网 时间:2024/06/06 06:35

变量在定义时被分配内存,并且变量可以指定一个初始化的值。变量只能在这个程序中定义一次。声明在该程序中指定了变量的类型和名称。定义也是一种声明:当我们定义一个变量时,我们声明了它的名字和类型。我们也可以通过使用extern关键字来声明一个变量的名字而不用定义。

  一个声明可以是加extern前缀的并包含了目标的类型和名称,如:

  点击(此处)折叠或打开

  extern int i; //声明了i但是并未定义

  int i;

  加extern关键字的声明不是定义并且不分配内存(实际上声明是不分配内存的)。实际上,它只是宣称了已经在其它文件中定义的变量的名称和类型。一个变量可以声明多次,但是只能定义一次。声明只有在他同样是定义时才能初始化,因为只有定义才会分配内存。

  如果一个声明初始化,那么它就被当做定义,即便已经被extern标记,例如

  点击(此处)折叠或打开

  extern double pi = 3.1416; //定义

  尽管使用了extern,它还是定义了pi.该变量分配了内存并初始化。只有出现在函数的extern声明才可能初始化。因为被当做定义,所以后续的任何对该变量的定义都是错误:

  点击(此处)折叠或打开

  extern double pi = 3.1416; // 定义

  double pi; // 错误:重定义pi

  我对定义和声明的认识是:

  定义给变量分配了内存,并且只能定义一次,如 int i = 0;

  声明没有给变量分配内存,可以声明多次,最常用的是函数参数的声明如 void main(int a, int b);这里面的a和b都未分配内存,只是说明了变量的名称和数据类型。

  注:《C Primer Plus》上的原文资料

  A definition of a variable allocates storage for the variable and may also specify an initial value for the variable. There must be one and only one definition of a variable in a program.A declaration makes known the type and name of the variable to the program. A definition is also a declaration: When we define a variable, we declare its name and type. We can declare a name without defining it by using the extern keyword. A declaration that is not also a definition consists of the object's name and its type preceded by the keyword extern:

  extern int i; // declares but does not define i

  int i; // declares and defines i

  An extern declaration is not a definition and does not allocate storage. In effect, it claims that a definition of the variable exists elsewhere in the program. A variable can be declared multiple times in a program, but it must be defined only once.

  A declaration may have an initializer only if it is also a definition because only a definition allocates storage. The initializer must have storage to initialize. If an initializer is present, the declaration is treated as a definition even if the declaration is labeled extern:

  extern double pi = 3.1416; // definition

  Despite the use of extern, this statement defines pi. Storage is allocated and initialized. An extern declaration may include an initializer only if it appears outside a function.

  Because an extern that is initialized is treated as a definition, any subseqent definition of that variable is an error:

  extern double pi = 3.1416; // definition

  double pi; // error: redefinition of pi

原创粉丝点击