C Global Variables & C Local Variables: C Variable Scope
By the scope of variables in c, we mean that from which parts of the program any particular variable could be accessed. Thus, depending on the scope of variables in c language, variables could be classified as follows:
Global Variables
Global variables in c have their declaration outside the function definition of all functions used with in the program and remains in the memory as long as the program is executing.
All global variables in c could be accessed from anywhere in program which means that any expression in the program can access the global variable regardless of what block that expression is written.
Thus, the global variables have their scope global.
For example,
/*Program to illustrate c global variables*/ #include<stdio.h> int a=5; main() { ++a; printf("%dn",a); increment(); return 0; } void increment() { ++a; printf("%dn",a); }
Output
6
7
Local Variables
Local variables are declared with in a function definition and thus could only be accessed from anywhere in that function in which it is declared. Thus, local variables have their scope local to the function in which they are declared and are unknown to other functions outside their own function.
Local variables are defined and initialized every time a function containing them is called and as soon as the compiler exits from that function, the local variable is destroyed.
For example,
/*Program to illustrate c local variables*/ #include<stdio.h> main() { int a=5; ++a; printf("%dn",a); increment(); return 0; } void increment() { ++a; printf("%dn",a); }
Output
In the above program, an error will occur as in the function increment() we are trying to access variable “a” which is not known to it. It should be noted that the variable “a” is local to the function main().
No Comments
at