Global Variable in C
Definition of Global Variable:
Global variables are the variables which are declared outside of all the functions and thus its life exists untill the life of program.
It can be accessed anywhere in the program i.e it have a global scope.
By using the keyword ‘extern’ global variables can be accessed in other files also.
Example:
//fileA.c int x; int main() {x=10; } //fileB.c extern int x; //This is only declaration, its definition exists in some other file, here it is in fileA.c int function1() { x=10; //fileB.c can access 'x' if fileA.c is linked with it. }
Initialization of Global Variable:
By default, global variables are initialized by zero ‘0’ by the compiler, this means when we print the value of an uninitialized global variable it will not give garbage value as output.
So it is very much clear that global variables are initialized at the time of compilation not at run time, and because of this reason we can only assign constants in a global variable.
Example 1:
//fileA.c #include#include float *x=(float*)malloc(sizeof(x)); int main() { *x=35.56; printf("%f",*x); } output in C: Compile error: initializer element is not constant. Output in C++: 35.56
Example 2:
//fileB.c #includeint function1(int a) { return a; } int b=function1(10); // calling function1 and storing its return value in global variable int main() { printf("Hello, i am main\n"); printf("%d",b); } output in C: Compile error: initializer element is not constant. Output in C++: Hello, i am main 10
As we can see, the above programs works fine in C++ but not in C.