該樓層疑似違規已被系統折疊?隱藏此樓查看此樓
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)只有在一種情況下可以被初始化,那就是當他被放置在函數外部的時候。