1.

Discuss the similarities and difference between global and local variables in terms of their lifetime and scope. 

Answer»

Local variable
Global variable
It is a variable which is declared within a function or within a compound statement.It is a variable which is declared outside all the functions.
It is accessible only within a function/compound statement in which it is declaredIt is accessible throughout the program
A global variable comes into existence when the program execution starts and is destroyed when the program terminates.A local variable comes into existence when the function is entered and is destroyed upon exit.

Example:

#include <iostream.h>

float NUM=900; 

//NUM is a global variable

void LOCAL(int T)

{

int Total=0; //Total is a local variable

for (int I=0;I<T;I++)

Total+=I; cout<<NUM+Total;

}

void main() {

LOCAL(45);

}



Discussion

No Comment Found

Related InterviewSolutions