简体   繁体   English

为什么全局变量不会掩盖局部变量(两者具有相同的名称)?

[英]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 .某些语言不允许在ifswitch等某些块中声明内部变量(同名)。 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.

相关问题 当“全局”,“本地”和“非常本地”变量存在同名时,如何访问“本地”变量 - How to access “local” variable when a “global”, “local” and “very local” variable exist having same name Java中的局部变量,与全局变量同名 - Local variable in Java with the same name as a global variable 为什么 Python 不允许将全局变量分配给具有相同名称的本地变量? - Why doesn't Python allow assigning a global variable to a local one with the same name? Bash:使用具有相同名称的局部变量隐藏全局变量 - Bash: Hide global variable using local variable with same name 在JS中无法传递具有全局变量名称的局部变量? - Passing local variable with name of a global variable isn't possible in JS? 全局和局部变量名冲突 - Clashing global and local variable name 如何在C中访问同名的局部和全局变量 - How to access local and global variable with same name in C 为什么局部作用域不引用全局变量? - Why a local scope doesn't refer on a global variable? 访问与实例变量同名的全局变量 - Access global variable with same name as instance variable 为什么这个对非本地作用域的变量引用无法解析? - Why won't this variable reference to a non-local scope resolve?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM