Could someone exactly explain the concept of scope and life of variable in C. Is it different in C++? I'm confused between scope and life.
See Question&Answers more detail:osCould someone exactly explain the concept of scope and life of variable in C. Is it different in C++? I'm confused between scope and life.
See Question&Answers more detail:os"Scope" of a variable is a region of source code, where you can refer to that variable.
"Lifetime" is how long it exists during the program execution.
By default the lifetime of a local variable is the same as its scope:
void foo()
{
int x = 123;
cout << x << endl;
x += 1;
}
int main(){ foo(); foo(); foo(); }
Here, each time foo
is called a new x
is created (space is reserved for it on the stack), and when the execution leaves the block where x
was declared, x
is destroyed (which for int
just means that the space that was reserved, now is freed for reuse).
In contrast:
void foo()
{
static int x = 123;
cout << x << endl;
x += 1;
}
int main(){ foo(); foo(); foo(); }
Here, since x
is declared static
, space is reserved for x
before the program execution even begins. x
has a fixed location in memory, it's a static variable. And C++ has special rules about the initialization of such a variable: it happens the first time the execution passes through the declaration.
Thus, in the first call of foo
this x
is initialized, the output statement displays 123, and the increment increases the value by 1. In the next call the initialization is skipped (it has already been performed), the value 124 is output, and the value is incremented again. So on.
The lifetime of this x
is from start of execution to end of execution.