Global variables in C

Previous
Next

Global variables:

  • Declaration of variables outside to all the functions.
  • We generally declare the local variables above all functions in source code.
  • Global variables automatically initializes with default values.
DatatypeDefault value
Int0
Float0.000000
CharBlank
PointerNULL
#include <stdio.h>
int a;
float b;
char c;
int *p;
int main()
{
	printf("int val : %d \n", a);
	printf("float val : %f \n", b);
	printf("char val : %c \n", c);
	printf("pointer val : %s \n", p);
   	return 0;
}

Output:
int val : 0
float val : 0.000000
char val :
pointer val : (null)
  • Every pointer variable stores address.
  • If there is no assigned address, by default it is pointing NULL address.
  • We discuss briefly in pointers concept.
  • Any pointer type default value is ‘null’ only.
  • Following program shows the null values as output.
  • We can access global variables anywhere in the program.
  • We can access from all function which are defined in the program.
#include <stdio.h>
int a=10;
int main()
{
    printf("In main : %d \n", a);
    test(); 
   	return 0;
}
void test()
{
    printf("In test : %d \n", a);
}

Output:
In main : 10 
In test : 10

Note: Local variables and Global variables can have the same name. When we access variable inside the function, it gives the first priority to local variable.

#include <stdio.h>
int a=10;
int main()
{
    int a=20;
    printf("In main : %d \n", a);
    test(); 
   	return 0;
}
void test()
{
    printf("In test : %d \n", a);
}

Output:
In main : 20 
In test : 10
Previous
Next

Add Comment

Courses Enquiry Form