When do formal parameters not hide external variables?
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?
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.
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! :)
In languages with dynamic scoping, the inner x
wouldn't hide the outer x
, it would modify the outer x
. 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.
精彩评论