2017-10-16 132 views
3

我想了解C++中的存儲類說明符。我有兩個例子。在C++中給定的相同範圍內聲明相同的變量名稱

這裏,在給定的相同範圍內,聲明相同的變量名稱。

情況1:

#include <iostream> 

static int i; 
extern int i; 

int main() { 
    std::cout<<i<<std::endl; 
    return 0; 
} 

輸出:

0 

情況2:

#include <iostream> 

extern int i; 
static int i; 

int main() { 
    std::cout<<i<<std::endl; 
    return 0; 
} 

獲得一個錯誤:

prog.cpp:4:12: error: 'i' was declared 'extern' and later 'static' [-fpermissive] 
static int i; 
      ^
prog.cpp:3:12: note: previous declaration of 'i' 
extern int i; 

爲什麼第一個案件工作正常,而第二個案件給出錯誤?

+1

看起來更像是C++ - 你確定你有正確的標籤嗎? –

回答

13

extern有點奇怪,因爲用它標記的聲明會查找同一個實體的先前聲明,如果它找到一個聲明,它就會使用以前的鏈接。只有當它沒有找到一個它宣佈一個新的實體與外部鏈接。

static另一方面,無條件地聲明其實體內部鏈接。

這意味着該代碼只是聲明和定義i與內部鏈接。第二個聲明找到第一個聲明並重新使用它的鏈接。

static int i; 
extern int i; 

鑑於此代碼聲明變量具有外部鏈接,然後聲明和定義它具有內部鏈接,這是一個錯誤。

extern int i; 
static int i; 

針對此行爲的原因是難以跟蹤,但最有可能達到回方式C.

的預標準天在C++中,此行爲是由[basic.link]指定在最近的N4687草案中爲6.5/6:

The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage. If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external linkage.

相關問題