This blog is under construction

Saturday, 12 May 2012

Local variable vs global variable in C with example

Difference between local variables and global variable in C language

Local Variables:
Local variables are variables that are declared inside within any function body.  These variables are active within the block in which they are declared.

Example:
main() {
          int i, j, k;
          -------
          -------
}

void fun() {
          int num1, num2;
          -------------
          -------------
}


Global Variable:
Global variables are variables that are declared outside of all the function and it is active throughout our C program.  By default, global variables are initialized to 0

Example:
int num1, num2;
main() {
        int a;
        -------
        num1 = 100;
        --------
}

void fun() {
        int b;
        ------
        num1 = 200;
        num2 = 300;
        -------
}


Example C program using local variables and global variables
 
  #include <stdio.h>

  void print_Val();
  int global;

  int main() {
        int a;
        printf("Enter a number:");
        scanf("%d", &a);
        global =  100;
        print_Val(a);
        return 0;
  }

  void print_Val(int val) {
        printf("Inside print_Val() function:\n");
        printf("Local Variable value: %d\n", val);
        printf("Global variable value: %d\n", global);
  }


  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter a number:123
  Inside print_Val() function:
  Local Variable value: 123
  Global variable value: 100


No comments:

Post a Comment