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


1 comment:

  1. Dell Laptop Service center are giving repair service at the door. We should high quality Dell out of warranty Laptop Repair, removal of virus, screen removal, wireless network set up, battery removal, motherboard replacement to several other are offered at budget friendly price and it’s Negotiable. We can fix them all in time by our well experience and certified technicians. If you want to repair your laptop in front of your eyesight, than you may call us: 7217871051

    ReplyDelete