what is the difference b/w a normal global variable and a global static variable
Hi,
Can anyone explain me about the difference b/w a normal global variable and a global static variable.
ex:
if i have code like
int i;
static int j;
both are global variable, what is the difference b/w these two variables.
Thanks
Re: what is the difference b/w a normal global variable and a global static variable
Global variable defined with static keyword has a scope limited to translation unit it is defined in. This variable is not "totally" global (possible to use in other source files), it is visible and usable only in this source file (translation unit, to be exact).
Re: what is the difference b/w a normal global variable and a global static variable
Upto my knowledge, even the normal global variable's scope also get expire at the end of the program. If we want to use a variable in more than 1 source file, we may have to use 'export' keyword.
This is what my understanding about global variables, pls clarify me on this.
Thanks
Kiran.
Re: what is the difference b/w a normal global variable and a global static variable
Okay, so maybe a little example:
File a.cpp:
Code:
int global = 0; //define global variable
static int static_global = 42; //define static global variable
void fun1() {
//function within the dame translation unit may access both global variables
global = 3;
static_global = 13;
}
File b.cpp:
Code:
//declare variables
extern int global;
extern int static_global;
void fun2() {
//function within another translation unit may not access
//static global variables defined elsewhere
global = 16; //OK
static_global = 102; //Linker error, undefined in this translation unit
}
export keywoord does not apply to variables.
Cheers
Re: what is the difference b/w a normal global variable and a global static variable
That's gr8, your example is very much clear.
Apart from this scope functionality, is there anything else difference is there ?, like memory allocation or initialization or accessing the variables and so .
Thanks
Re: what is the difference b/w a normal global variable and a global static variable
No, there is no difference. Both those cases are global variables, they behave in exactly the same way.
Generally, you should avoid using global variables. They introduce a place for various pitfalls, often leading to very long, depressing and furious debugging sessions.
Cheers