Local and Global variable


local variable and global variable
fig:- Local and Global variable

If the variable is defined outside the functions and Is accessible to all function throughout the program is called global variable. Its initial value will be zero(0). 

 

Similarly, a variable that is defined inside the function and is accessible to only the same function is called a local variable. Its initial value will be garbage value.  

 

\n print a new line and %d print an integer value.  

 


#include <stdio.h>
int a = 50//this is global variable
int main()
{
    int b = 10// this is local variable
    printf("the value of Global variable is %d \n"a);
    printf("the value of Local variable is %d \n"b);
    return 0;
}

output  

the value of the Global variable is 50 

the value of the Local variable is 10 

 

QUESTION:  take the value of GLOBAL VARIABLE  from the user and add it with the local variable.  


#include <stdio.h>
int a//this is global variable
int main()
{
    int b = 10// this is local variable
    printf("enter a value for global variable: ");
    scanf("%d", &a);
    printf("sum of Global variable and local variable is %d \n"a + b);
    return 0;
}

  

output  

the sum of the Global variable and local variable is 50 

 

 

NOTE: if we are using the same name to define the variable in both local or global then we will get local variable value, but if we want to print global variable value then we have to use the "extern" keyword inside the function but if we want to print local variable then we can give a command print outside the int bracket function.  let's be clear with the given function:- 

 

Program 


#include <stdio.h>
int a = 50// global variable
int main()
{
    int a = 10// local variable
    {
        extern int a;// calling global variable value here
        printf("the value of Global variable a is %d\n"a); // this line 
will print global variable as it is inside the main function
    }
    printf("the value of local variable a is %d\n"a); // this line will
 print local variable as it is outside the main function
    return 0;
}

output  

the value of global variable a is 50 

the value of local variable a is 10  


Follow our page for regular updates.

0 Comments