Possible Duplicate:
Scope vs life of variable in C
What exactly is the difference between the scope and lifetime of a variable in c? What is the scope and lifetime of a variable declared within a block inside a function?
Possible Duplicate:
Scope vs life of variable in C
What exactly is the difference between the scope and lifetime of a variable in c? What is the scope and lifetime of a variable declared within a block inside a function?
Lets say we have two functions:
void foo()
{
/* Do some stuff */
}
void bar()
{
int local_bar;
foo();
/* Do some more stuff */
}
In the function bar
the scope of the variable local_bar
is all inside the function bar
. When calling foo
the variable temporarily goes out of scope, i.e. it's not available from inside of foo
. However, the lifetime of the variable has not ended, it will only end when the function bar
ends.
It depends. Scope represents the blocks of code from which the variable can be accessed, lifetime represents the period from creation to destruction.
What is the scope and lifetime of a variable declared within a block inside a function?
In this case, they coincide:
{
int x; // begin scope and lifetime
} // end scope and lifetime
The difference arises in other cases, for example with globals. You declare an extern int x
and define it somewhere. Its lifetime extends from the start to the end of the program, but it's scope is only in the files where you actually include the declaration.