变量定义与声明的区别(3)

时间:2026-01-23

变量定义与声明的区别

带“extern”关键字的语句属于声明(declarations),不是定义(definitions),他不会给变量分配内存。实际上,它是说明程序中的某处包含这个变量的定义。一个变量可以在程序中被声明(declarations)多次,但是只能被定义(definitions)一次。

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: 声明(declarations)时你可以给变量初始化。但是一旦你这样做,那么这句话也就变成了定义(definitions),因为只有在定义(definitions)的时候才会为变量分配内存。初始化的时候必然要为初始值分配存储空间。如果你在声明(declarations)的时候同时初始化了变量,即便“extern”关键字存在,这个语句也会认为是定义(definitions)。

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.

不管有没有“extern”关键字存在,这条语句的作用也是定义(definitions)“pi”。变量已经被分配了内存,并且赋予了初始值。声明(declarations)只有在一种情况下可以被初始化,那就是当他被放置在函数外部的时候。

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

由于包含初始化的声明(declarations)语句会被认为是定义(definitions),所以如下的用法会被认为是错误的:

Similarly, a subsequent extern declaration that has an initializer is also an error:

变量定义与声明的区别(3).doc 将本文的Word文档下载到电脑

精彩图片

热门精选

大家正在看

× 游客快捷下载通道(下载后可以自由复制和排版)

限时特价:4.9 元/份 原价:20元

支付方式:

开通VIP包月会员 特价:19元/月

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信:fanwen365 QQ:370150219