c语言中void plusone,C语言中定义与声明的区别

刚学C语言的时候,我甚至都没有听过声明和定义,根本不知道它们到底有什么联系,老师在课堂上也没有解释两者的区别。我在网上搜到了经典作品《C primer plus》的原版资料,顺便翻译了一下,同时附上我自己的见解。

变量在定义时被分配内存,并且变量可以指定一个初始化的值。变量只能在这个程序中定义一次。声明在该程序中指定了变量的类型和名称。定义也是一种声明:当我们定义一个变量时,我们声明了它的名字和类型。我们也可以通过使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值