Static variables
I dont'' seem to be able to get my head around what exactly a static variable is and why it is useful. I seem to be able to find explanations but it helps me understand better if I can see a working example.
Could someone please explain to me exactly what a static variable is and when it is useful and why it should be used over a global variable or whatever.
Thanks
August 05, 2002 09:58 AM
A "C" answer....
static locals are local variables which aren''t re-initialised or created/destroyed in the function scope. They are really just global variables which have function-local scope.
static globals have file scope, i.e. a static defined in a cpp file can only be used below the declaration of said variable in the file. It''s a bit like making the variable "private" to the file. No-one can extern it or access it from another source file.
A "C++" answer...
Don''t use static globals, use an unnamed namespace instead for the same effect.
Static locals are the same as in C, except static class variables are constructed for the first time when the function is first called, and destroyed at program exit.
Static class members are like global variables associated with a class, in that all instances share the exact same variable. The variable is constructed before the program begins and destroyed at program exit. If they are private or protected though, only member functions have access. If they are public, they are exactly like normal globals except they are scoped in the class.
static locals are local variables which aren''t re-initialised or created/destroyed in the function scope. They are really just global variables which have function-local scope.
static globals have file scope, i.e. a static defined in a cpp file can only be used below the declaration of said variable in the file. It''s a bit like making the variable "private" to the file. No-one can extern it or access it from another source file.
A "C++" answer...
Don''t use static globals, use an unnamed namespace instead for the same effect.
Static locals are the same as in C, except static class variables are constructed for the first time when the function is first called, and destroyed at program exit.
Static class members are like global variables associated with a class, in that all instances share the exact same variable. The variable is constructed before the program begins and destroyed at program exit. If they are private or protected though, only member functions have access. If they are public, they are exactly like normal globals except they are scoped in the class.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement