How do the compiler know it is out of scope?
Main()
{
int i =0;
...
...
while(true开发者_运维百科)
{
int k =0;
...
...
}
// K is out of scope..
}
How does the compiler know K is out of scope?
How does the compiler know [that a local variable] is out of scope?
First off, let's carefully define the terms you're using. The scope of a named entity is the region of program text in which it is legal to use the name of the entity without additional qualification of the name.
The scope of a local variable is defined by the specification as the region of program text which is the entire block that immediately contains the declaration.
The compiler determines the scope of the local variable by keeping track of a local declaration space associated with each syntactic block. When we need to resolve a name, we figure out what block the name usage is inside, and consult the related declaration space. Of course, blocks nest and so do local variable declaration spaces, so we might have to consult more than one, in order from inside-to-outside.
The actual data structures we use are straightforward hash tables optimized for fast lookup and filtering on various aspects needed by the compiler. (For example, we sometimes need to look up names but only want to get types, or only methods, and so on.)
Does that answer your question? It's a rather unclear question.
Because as the compiler processes the code it maintains information about each identifier it comes across and each scope it comes across and maintains boundaries for the latter. It knows that K was declared in the while scope and after the scope ends it probably marks the variable as 'no longer in scope' causing any use to be marked as an error.
k
is out of scope because the block it was defined in is closed.
I would say it's a meaningless question. K is out of scope because you wrote the program that way: the compiler's entire function is to recognize and translate the programming language, including the lexical scope aspect of it.
精彩评论