形式参数什么时候不隐藏外部变量?
序言
因此,我正在学习C 编程语言
,这句话让我印象深刻:
自动变量,包括形式参数,也隐藏同名的外部变量和函数。
示例:
int x;
// x inside of f is different from external f.
void f(double x){}
TL;DR
这对我来说是所有语言都必然成立的东西(它可以追溯到 Lambda Calc.),但它却出现在本书中。是否有一个例子,其中变量的最本地定义不会覆盖更全局的定义?
Preamble
So, I'm going through The C Programming Language
and this quote struck me:
Automatic variables, including formal parameters, also hide external variables and functions of the same name.
The example:
int x;
// x inside of f is different from external f.
void f(double x){}
TL;DR
This strikes me as something which is necessarily true of all languages (and it dates back to Lambda Calc.), and yet it makes it into this book. Is there an example where the most local definition of a variable does not override a more global definition?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它绝对不是语言的必要条件。碰巧的是,我能想到的所有语言都以这种方式处理它们的范围。为什么?可能是因为长期以来一直都是这样做的,而且对于编译器和程序员来说都是最有意义的(想想堆栈)。
然而,当我在学校时,我用一种解释语言做了一个实验,其中符号被放入队列中。因此,最全局的作用域覆盖了局部作用域。该语言仍然有效并且功能齐全。唯一的区别是局部作用域被全局作用域覆盖。归根结底,就是在更全局的范围内小心命名。
Its definitely not a necessary condition for a language. It just so happens that all the languages I can think of handle their scopes in this way. Why? Probably because that's how it has been done for so long and it makes the most sense, both for the compiler and the programmer (think about stacks).
However, while I was in school, I did an experiment with an interpreted language in which symbols were put in a queue. As such, the most global scope overrode the local scopes. The language still worked and was fully functional. The only difference was that local scopes were overridden by global scopes. What this boils down to is just being careful about your naming in more global scopes.
这是一场斗争,但我发现了一个非常非常弱的 示例 全局变量覆盖局部变量。确实不算数,但这是我能找到的全部!
我确信 K&R 中包含了解释,因为他们不想假设以前有编程经验。局部作用域压倒全局作用域是我们大多数人的第二天性,但新鲜的头脑不会有这种知识。明确地陈述它会让你思考为什么它可能是真的,这会带来启蒙! :)
It was a struggle, but I found a very, very weak example of a global variable overriding a local one. It doesn't really count, but it's all I could find!
I'm sure that explanation was included in K&R because they didn't want to assume prior programming experience. Local scope overriding global scope is second nature to most of us, but a fresh mind wouldn't have that knowledge. Stating it explicitly causes you to think about why it might be true, and that leads to enlightenment! :)
在具有动态作用域的语言中,内部
x
不会隐藏外部x
,它会修改外部x
。请参阅维基百科页面上的示例。在编写 K&R 时,具有动态作用域的语言(尤其是 Lisp 方言)更为常见。然而,动态作用域与任何类型系统的交互都很差,即使是像 C 那样松散执行的类型系统。In languages with dynamic scoping, the inner
x
wouldn't hide the outerx
, it would modify the outerx
. See the example on the wikipedia page. Languages with dynamic scoping, particularly dialects of Lisp, were more common when K&R was written. Dynamic scoping interacts poorly with any sort of type system, though, even a type system as loosely enforced as C's.