Tuesday, March 22, 2011

Program for The Concept Of Global Variable with Explanation


Program

#include <stdio.h>
int i =0;     //Global variable
main()
{
    int j;          // local variable in main
    void f1(void) ;
    i =0;
    printf("value of i in main %d\n",i);
    f1();
    printf("value of i after call%d\n",i);
}
void f1(void)
{
    int k;            // local variable for f1.
    i = 50;
}

Explanation

  1. When you define a variable inside the function block it is called a local variable.
  2. The local variable can be accessed only in the block in which it is declared.
  3. j is the local variable for main and it can be accessed only in the block main. That means you cannot access it in function f1.
  4. k is the local variable for function f1 and it cannot be accessed in main.
  5. The variable i, which is outside main, is called a global variable. It can be accessed from function main as well as function f1.
  6. Any expression in this function is going to operate on the same i.
  7. When you call function f1, which sets the value of i to 50, it is also reflected in main because main and f1 are referring to the same variable, i.

No comments:

Post a Comment