Difference Between Global , extern global , static , static global.



int i = 10; // file1.h /cpp
1. Defines a global variable, allocating memory for it which will  be accessible by all files in the program.


extern int i; // file2.h/cpp
2. Declares a global variable which is defined in another file. No memory is allocated. This is how global variables defined in one file can be used in another.


static int i = 10; //  local variable in some function myfun()
3. static local variables retain their values on repeated calls into the function unlike other local variables.


static int i = 10; // Global variable in file3.h
4. These global variables can only be accessed from within the file. Using the static keyword you can declare global variables with the same name in multiple files in the same program.It is helpful to restrict the scope of that variable to that file only in which it is declared. You can declare another global variable in another file with same name. (But this is not the case with the non-static global variables)


Comments

Popular Posts