[英]Is Declaration of Variable in C Limited to Extern Keyword Alone Vs Definition
我懷疑有什么我不知道尋求宣言和定義之間的區別,我找到了鏈接https://www.geeksforgeeks.org/commonly-asked-c-programming-interview-questions-set-1/它在此聲明
// This is only declaration. y is not allocated memory by this statement
extern int y;
// This is both declaration and definition, memory to x is allocated by this statement.
int x;
現在,如果我按下面的代碼
int main()
{
{
int x = 10;
int y = 20;
{
// The outer block contains declaration of x and y, so
// following statement is valid and prints 10 and 20
printf("x = %d, y = %d\n", x, y);
{
// y is declared again, so outer block y is not accessible
// in this block
int y = 40;
x++; // Changes the outer block variable x to 11
y++; // Changes this block's variable y to 41
printf("x = %d, y = %d\n", x, y);
}
// This statement accesses only outer block's variables
printf("x = %d, y = %d\n", x, y);
}
}
return 0;
}
我會得到以下結果
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20
如果我只修改最里面的塊中的int y = 40到y = 40那么代碼看起來就像
// int y;
int main()
{
{
int x = 10;
int y = 20;
{
// The outer block contains declaration of x and y, so
// following statement is valid and prints 10 and 20
printf("x = %d, y = %d\n", x, y);
{
// y is declared again, so outer block y is not accessible
// in this block
y = 40;
x++; // Changes the outer block variable x to 11
y++; // Changes this block's variable y to 41
printf("x = %d, y = %d\n", x, y);
}
// This statement accesses only outer block's variables
printf("x = %d, y = %d\n", x, y);
}
}
return 0;
}
結果將是
x = 10, y = 20
x = 11, y = 41
x = 11, y = 41
我的朋友告訴我這是因為我們在第一個代碼中聲明一個新的y是塊的本地,而不是在第二個例子中,我不明白為什么因為我們只在前面寫了數據類型變量第二次,這是否意味着通過寫入數據類型我們保留了一個新的內存空間並創建了一個新變量,請解釋一下。
如果我在鏈接上的另一篇關於Stackoverflow的文章中, 定義和聲明之間的區別是什么?
我看到,每當我們說我們聲明一個變量時,變量前面都是extern關鍵字,而且我說的是與C嚴格相關而不是任何其他語言。
因此,我們可以推廣到extern關鍵字之前的變量聲明。
我理解我的英語可能很難理解,請耐心等待。
{
// y is declared again, so outer block y is not accessible
// in this block
y = 40;
你的評論是錯誤的。 這不是聲明 y
一次。 它只是分配給它。
它應該說:
// This changes the value of y in the outer block
這意味着通過寫入數據類型我們保留了一個新的內存空間並創建了一個新的變量
是。
int y
是新變量的聲明。 int y = 40
是聲明和初始化。 y = 40
是對現有變量的賦值。 extern int y;
告訴編譯器y
可以在鏈接到該程序的另一個文件中聲明,無論是庫,頭文件等,如果編譯器發現名為y
全局變量,那么它應該使用其內存地址為y
在此文件中聲明。 即:
//Look for a global variable called "y" in the included files
//If it is found, use its memory address
extern int y;
現在,為您的第一個代碼示例...
首先,聲明並實例化兩個變量x
和y
。
int x = 10;
int y = 20;
然后打印它們,結果打印x = 10, y = 20
。 這是有道理的,因為x
是10而y
是20。
然后,使用花括號創建一個新范圍,並聲明一個名為y
的新變量。 由於此變量與高於它的作用域中的變量具有相同的名稱,因此它會隱藏名為 y
的外部變量,直到退出此作用域。
{
int y = 40;
對此 y
任何更改都不會影響外部y
,並且在退出此 y
的范圍之前無法訪問外部y
。
然后遞增x
和y
,然后打印結果。 由於上述行為x = 11, y = 41
。
打印上面的字符串后,代碼退出當前范圍。 因此,外部y
不再被隱藏,現在可以訪問它。
最后,再次打印x
和y
。 x
是11,因為它先前遞增,但外部y
沒有增加 ,因此x = 11, y = 20
被打印。
將int y = 40
替換為y = 40
就像在第二個代碼示例中所做的那樣,只會聲明並實例化一個y
變量。 因此, y
在第三個printf()
語句中最終為41。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.