Scope vs life of variable in C
c, c++
Solution
Scope is the region where the variable is accessible. Life time is the time span during which an object remains valid.
An simple example:
#include <iostream.h>
void doSomething()
{
x = 5; //Error! Not Accessible
}
int main()
{
int x = 4;
std::cout<< x << endl;
{
int x = 2;
cout << x << endl;
}
doSomething();
std::cout<< x << endl;
return 0;
}
The above gives the output:
4 2 4
In above program, lifetime of variable `x = 4` is throughout the main, i.e: It remains alive throughout the execution of the main, Also it is accessible within the main, that is its scope. Note that it is not accessible in the function because it is beyond the scope of the variable `x`.
while scope and lifetime of variable `x = 2` is within the enclsing braces`{` `}` inside the main.
Problem
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.