The life time of a variable represents the period of time du

The life time of a variable represents the period of time during which it can hold a value. In other words, it is between when the variable is created in the memory until it is de-allocated from the memory. The book discussed the concept of scope. Is life time the same as scope? If not, what is the difference?

Solution

Life time refers to till the time the varaible can stay in existence in the program

i.e till the memory gets de-allocated or till the end of the program.

Scope refers to the reachability of the variable.

Hence life time is not the same as scope.

Example,

consider the following function,

void add(int a, int b)
{
int c = a + b;
}

int main()
{
   // at this point c is not accessible since its scope ended within the add function.
   // i.e within the curly braces of add.
   // we cannot access c here, wheher or not the variable is existing in the memory.
}

The life time of a variable represents the period of time during which it can hold a value. In other words, it is between when the variable is created in the me

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site