Jun 30, 2014

C Programming #33: Global Variable

Following article will discuss about the global variables. Till now all the variables we have used/discussed are local variables.

Let us consider an  example




#include <stdio.h>

int g = 10;

int func();
int main() 
{
   int m = 1, x;
   x = func();
   g = x;
   return 0;
}

int func()
{
   int f = 5;
   return g;
}

Explanation:
  • 'g' is called global variable
    • It can be accessed from main as well as any other function.
  • 'm' is local variable to main
    • It can be accessed only from main not from any other function
  • 'f' is local variable to func
    • It can be accessed only from func and not from main, or any other function.
'g' is allocated in data section, while 'm' and 'f' in stack section. More of which is covered in future topic - C Programming #34: Journey from source code to executable.

Links

Next Article - C Programming #34: Journey from source code to executable
Previous Article - C Programming #32: Function
All Articles - C Programming

No comments :

Post a Comment