[英]Why not global variable won't masks local variable (Both having same name)?
As we all know it's a standard that local variable masks the scope of global variable if both are having same name.众所周知,如果两者具有相同的名称,则局部变量会掩盖全局变量的 scope 是一种标准。
Example:-例子:-
int x=10;诠释 x=10;
int main()主函数()
{ {
#local variable x masks the scope of global variable x in the main function. #local variable x 掩盖了主 function 中全局变量 x 的 scope。
int x=5;诠释 x=5;
printf("%d",x); printf("%d",x);
} }
My question is that, What is the reason behind the standard and why global variable never masks the locals variable?我的问题是,标准背后的原因是什么以及为什么全局变量从不掩盖局部变量?
In simple language, Inner variables mask outer/global variables because we can control them "easily".用简单的语言来说,内部变量掩盖了外部/全局变量,因为我们可以“轻松地”控制它们。 If global variables were to mask inner variables then there would be no point in declaring inner variables.
如果全局变量要掩盖内部变量,那么声明内部变量就没有意义了。
You can read more about variable shadowing/masking in this article https://en.wikipedia.org/wiki/Variable_shadowing您可以在这篇文章https://en.wikipedia.org/wiki/Variable_shadowing中阅读有关可变阴影/遮罩的更多信息
This behaviour is always dependent on the name resolution rules of a particular language.此行为始终取决于特定语言的名称解析规则。 Some languages doesn't allow to declare inner variables(same name) in certain blocks like
if
and switch
.某些语言不允许在
if
和switch
等某些块中声明内部变量(同名)。 You can read more about this here - https://en.wikipedia.org/wiki/Name_resolution_(programming_languages)#Name_masking您可以在此处阅读更多相关信息 - https://en.wikipedia.org/wiki/Name_resolution_(programming_languages)#Name_masking
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.