extern keyword in C rules [duplicate]

心已入冬 提交于 2021-02-10 09:53:33

问题


Why does the following piece of code work -

extern int i;    
main()
{
   int i = 10;
   printf("%d", i);
}

but this one doesn't -

main()
{
   extern int i;
   int i = 10;
   printf("%d", i);
}

回答1:


As already stated in comments, in the first fragment there are two distinct variables; scoping rules make that the local (inner) variable hides the outer one, but there are still two.

In the second fragment there is the temptative of declaring two times the same identifier, and the declarations collide each other.




回答2:


Because extern means that the variable is defined elsewhere. You can define a variable from the global scope somewhere else (well, because it's global, so it's shared :) ), but you can't define a local variable elsewhere, because the function body is right here. If you could somehow split the function body in two between two files, declare this variable in one block, and then refer to it in another using extern, that would sort of make sense... But it's not possible, so extern inside a function body is meaningless.

UPD: I didn't notice that there are two variables in both cases, sorry. @linuxfan's answer applies better in this situation. I'll leave this answer here just in case it will be helpful for anyone (as additional details).




回答3:


In your first snippet. You're declaring that a global variable 'i' exists and has been declared elsewhere in some file that is included elsewhere in your project.

Other functions in the main file will be able to access that variable. The main function in the main file creates a local variable with the same name, and so will not be able to access the global 'i' variable.

The second snippet has two mistakes. 1) You are trying to declare a local extern variable - this is invalid. 2) You are trying to declare to variables in the same scope with the same name.



来源:https://stackoverflow.com/questions/51761151/extern-keyword-in-c-rules

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!