【发布时间】:2018-10-24 12:29:08
【问题描述】:
我怀疑在寻求声明和定义之间的差异时我缺少一些东西,我找到了链接 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 的另一篇文章 What is the difference between a definition and a declaration?
我看到,每当我们说我们声明一个变量时,变量前面都有 extern 关键字,我说的是与 C 语言而不是任何其他语言严格相关。
所以我们可以概括为以extern关键字开头的变量声明。
我知道我的英语可能很糟糕,你很难理解,请多多包涵。
【问题讨论】:
-
如果您正在学习 C,那么阅读 C++ 答案并没有多大帮助。
标签: c