gaurav said:
The lifetime of a variable is how long it lives. A variable stops
"living" when it goes out of scope and is no longer accessable. A
variable's scope is the block in which it is contained.
Correct????
First sentence correct, second incorrect, third correct
(pretty much).
"Scope" is a property of identifiers, not of variables
as such: An identifier can designate a variable, or a function,
or a macro, or an enum constant, or various other things in a C
program. The program can use the same identifier to refer to
different things at different places -- in different "scopes."
For example, `x' can be one function's first parameter, can
refer to an auto variable in some other function, can be the
name of a struct element somewhere else, and so on. The scope
of each of these uses is the region of program source in which
`x' has the same meaning. Silly example:
int f(void) {
int x = rand() - RAND_MAX / 2;
return x < 0 ? g(x) : h(x);
}
int g(int z) {
return z + 42;
}
int h(int a) {
x:
--a;
if (a % 2 == 0) goto x;
return a;
}
This example uses the identifier `x' to mean two different
things in two different scopes: It is an auto variable in
the function f(), and it is a label in the function h().
`x' has no meaning at all in function g().
Now: When the execution of f() gets as far as the
declaration, an auto variable comes into existence and remains
in existence until f() returns. Within the scope of f(),
the identifier `x' refers to that variable. But what if f()
calls g()? Inside g(), `x' means nothing; the identifier is
not in scope, even though the variable it once named still
exists (because f() hasn't returned yet). Or what if f()
calls h()? Inside h(), `x' is a statement label and does
not refer to a variable at all -- yet f() still has not
returned and its auto variable still exists.
Scope is a lexical property; lifetime is a dynamic property.