Sunday 20 May 2012

Differentiate between Global & Local variables with examples


Local Variable
Global Variable
Local variables are declared inside a function.
Global Variables are declared before the main function.
Local Variables cannot be accessed outside the function.
Global Variables can be accessed in any function.
Local Variables are alive only for a function.
Global Variables are alive till the end of the program.

Example of local variable.
//program to add any two integers
void main()
{
int a,b,sum;
clrscr();
printf("Enter any two integer value");
scanf("%d%d",&a,&b);
sum=a+b;
printf("\nSum of two integers %d and %d is %d",a,b,sum);
}
Here, a,b, and sum are local variables which are declared in main function.

Example of global variable.
//program to find the sum and difference between two numbers
int a,b,result;
void main()
{
clrscr();
sum();
sub();
getch();
}
sum()
{
printf("Enter two numbers to find their sum");
scanf("%d%d",&a,&b);
result=a+b;
printf("\n the sum of two numbers is %d",result);
return 0;
}
sub()
{
printf("Enter two numbers to find their difference");
scanf("%d%d",&a,&b);
result=a-b;
printf("\n the difference between two numbers is %d",result);
return0;
}
Here, a,b and result are global variables which are declared before the main function.

22 comments:

  1. Thank u
    The provided information is very nice

    ReplyDelete
  2. Thank u
    The provided information is very nice

    ReplyDelete
  3. this program is not working properly

    ReplyDelete