该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
http://ca21days.blog.163.com/blog/static/4383729420096102223744/
变量的声明(declarations)会将变量的类型和名称传达给程序。当然,定义
(definitions)也是一种声明:当我们定义一个变量的时候,我们当然也声明了他的名称和类型。我们可以通过使用“extern”关键字来声明
(declarations)一个变量,而不用定义(definitions)它。声明(declarations)的形式就是在对象(变量)的名字和类
型前面,加上关键字“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.
带“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)。
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.
不管有没有“extern”关键字存在,这条语句的作用也是定义(definitions)“pi”。变量已经被分配了内存,并且赋予了初始值。声明(declarations)只有在一种情况下可以被初始化,那就是当他被放置在函数外部的时候。