Friday 28 February 2014

Use of Local and global variable in function with example

Local and global variable
Local variable is defined within the body of the fucntion.Other function cannot access these variables.
Global variables-These are defined outside main () fucntion.Mulitiple functions can use them.

Write a program to show local variables.
#include<stdio.h>
#include<conio.h>
main()
{
    int a=10,b=20;
    clrcsr();
    printf("a=%d , b=%d",a,b);
}
func()
{
    int a=20,b=10;
    printf("a=%d b=%d",a,b);
}
Output
a=10,b=20
a=20,b=10
//here variable a and b are defined in both functions,There effect is only within the function in which they are defined//

Write a program to show global variables.
#include<stdio.h>
#include<conio.h>
int a =10,b=10;
main()
{
    clrcsr();
    printf("a=%d , b=%d",a,b);
    func();
    printf("a=%d , b=%d",a,b);
}
func()
{
   
    a++;   
    b--;
}
Output
a=10  ,b=10
a=11  ,b=9

No comments:

Post a Comment