Variables have a lifetime and scopes. Answer the questions based on the following C++ like code:
void fun1(void); /* prototype */
void main() {
static int ct = 0;
int *arr1 = new int [100];
double *arr2 = new double [50];
fun1();
delete []arr2;
fun2();
delete []arr1;
}
void fun1(void) {
int *arr3 = new int[50];
double ct = 0.0;
. . .
}
(1) What is the scope of variable arr1?
(2) What is the scope of variable ct defined in fun1?
(3) What is the lifetime of variable ct defined in main?
(4) What is the lifetime of a double array created in main?
(5) What is the lifetime of int array created in fun1.
Scope of a variable:
In programming languages scope of variable is parts or sections of the code where we can actually access that variable.All the parts of the code where we can access a variable is called as the scope of that variable.
Lifetime of a variable:
Lifetime of a variable refers to how long the variable exists in the memory of the program and can be accessible.
Answers to the given questions:
1)What is the scope of variable arr1?
The scope of the variable arr1 is only the main function.Because the variable arr1 is declared in the main function it can be accessed in the main function only.It cannot be accessed on other functions even though the functions are called in the main function.
2)What is the scope of variable ct defined in fun1?
The scope of the variable ct defined in fun1 function is only the fun1 function.Because if we declare a variable in a function it's scope upto that function only.
3) What is the lifetime of variable ct defined in main?
The lifetime of the variable ct defined in main is the entire lifetime of the program.Because it is defined as a static variable lifetime of a static variable equal to lifetime of the program.The static ct variable defined in main funcion exists in the memory until the program is completes.
4) What is the lifetime of a double array created in main?
The lifetime of the double array defined in main function is until we deleted the array using delete operator.This double array is created using new operator so the program allocates a memory in heap for this array and delete operator deallocates the memory in the heap when we delete that array.
5)What is the lifetime of int array created in fun1?
The lifetime of the int array created in fun1 is equal to life time of the program .Because the memory for this array is allocated dynamically using new operator so it will exist in the heap memory until the termination of the program unless we deallocate that memory using delete operator.
Get Answers For Free
Most questions answered within 1 hours.