C++, What is difference between static local variable(method) vs global(file) variable? - c++

A local static variable is created once and the method will go out of scope, but the static variable is not destroyed and it will live in memory until the program ends.
A global static variable live in memory until the program ends.
So what is difference between local and global static variables?
When should we use local static variables and global static variables?

Other answers have told you the differences between a local static object (local to a function) and a non-local static object (static objects declared global or in a namespace); however, you should also understand the importance of using one over the other.
The information I use here comes from Effective C++ Third Edition by Scott Myers (a recommended and excellent read)
A static object is one that exists from the time it's constructed until the end of the program.
As others have mentioned, a non-local static object is constructed before main whereas a local static object is constructed the first time the function is called.
But what if you had two static objects and one relied on the other. How could you be sure that one would be constructed before the other? You can't: The relative order of initialisation of non-local static objects defined in different translation units is undefined
Scott Myers definition of a translation unit (from aforementioned book):
A translation unit is the source code giving rise to a single object file. It's basically a single source file, plus all of the #include files.
So imagine you have these two non-local static objects in separate source files, you couldn't guarantee one would be constructed before the other. This is where a local static object prevails!
Consider Scott Myers' example of a FileSystem class and a Directory class, where the Directory relies on the FileSystem:
class FileSystem
{
public:
size_t numDisks() const;
};
extern FileSystem tfs;
and
class Directory
{
public:
Directory()
{
size_t disks = tfs.numDisks();
...
}
};
If Directory gets constructed before FileSystem, then you are going to be using an uninitialised class! Fortunately, you can get around this by using local static objects!
class FileSystem
{
public:
size_t numDisks() const;
};
FileSystem& tfs()
{
static FileSystem fs;
return fs;
}
Now when Directory is constructed, even if it's constructed before FileSystem is, FileSystem is guaranteed to be constructed before it's used!

An addition what others have said :
Scope and Lifetime are two different things.
Static variables' lifetime = Program's lifetime, that's why static variable is not destroyed and it will live in memory until program got end.
Scope means where we work with the variable/use the variable
Lifetime on the other hand is the complete execution time of the program, there may be certain cases where we terminate the program but in backgroud still bits and pieces are running.
When we have to use local static variable and global static variable?
We should use a local static when we need a variable restricted to that function only
We should use a global static when we need a variable common to all functions in the program. Eg:- A variable which contains the Budget of the organisation, whic is same for all departments
Hope this helps. Thanks

Differences I can think of:
The scope of the variable. A global static variable is visible to the entire program. A function static variable is visible only in the function.
Initialization. A global variable is initialized before main is executed. The function static variable is initialized when the function is called the first time.

A local static is visible only within the function. This allows the name to be kept secret. This could be used to implement profiling logic, where the number of calls for each function are tracked.
The more significant benefit of a local static, is the point in time when it is constructed. Global data is constructed before main is called. This occurs from the top of the file to the bottom of the file for each C++ file in the program, but the order of files in the construction is undefined. A local static is only constructed the first time it is called (C++ 11 guarantees only once, earlier C++ requires some synchronization if it can be called multi-threaded.) This means a complex object which requires some facility of your program to be initialized (e.g. some database) then this can be controlled as you can perform that initialization in main before your functions containing these static variables are called.

Global static variables can be accessed, and potentially changed, by other scopes. For example, two functions can share state using a global static variable. A local static variable is just that: local. Other functions cannot see it directly.
The fact that global static variables may be changed by other functions is a primary reason why they are so dangerous. Programmers often make unwarranted assumptions about the variable. For example, if a method uses, but does not modify a global static variable, it is still possible for the value to change from the beginning of the method to the end. People will tend to assume, however, that the value is unchanging.

A local Static is visible only inside the function, it has the scope of function level only, while Global Static has the program scope. And initialization, global is initialized at before main, local static would be initialized the first time function will get called.
Global Static variables if not used properly can cause issues, because in a large program it would be hard to keep track what is changing it's values.
Another possible drawback may be the linkage, what if you are using a global static variable named varnew and you are using an external library which also have the same variable.
It is always suggested to limit the scope of your variables to avoid unnecessary errors.

Related

Difference between declaring variables inside vs outside of main function

What is the difference between the following two ways of declaring variables in terms of performance??
1)
#include <iostream>
int main()
{
int x;//variable inside
//process
return 0;
}
2)
#include <iostream>
int x;//variable outside
int main()
{
//process
return 0;
}
Declaring a variable outside main function means that variable is global, while the one declared inside main is local. This is called "scope" and the concept applies to more than just main function. A better description of this can be found here and here.
Global variables are defined outside. They hold their value throughout the lifetime of your program. A global variable can be accessed by any function. It is available for use throughout your entire program after its declaration. This is called static duration. Variables with static duration are sometimes called static variables.
There are mainly two types of variable scopes:
- Your first part of the code is local variable for main(). You cant use int x outside of main(){}
- Second one is called global variable
Also unlike local variables, which are uninitialized by default, static variables are zero-initialized by default.
Check this,
As #Theodar explained Declaring a variable outside main is global and inside main is local. I wanted to explain the performance comparison using them.
Making the variable static may incur a small cost on every call of the function determining if the object was already initialized, especially with C++11 where the initialization is thread-safe. Even if it doesn't need a check, the stack is likely to be in cached memory while a static variable is not.
Making a variable global will increase the chances that it isn't in cached memory, i.e., there is a good chance that it will be slower (aside from adverse another potential like making it a good candidate to introduce data races).
Hope this will help you more.

Difference between static data member and global variable

Variations of this question might have been asked earlier as well. This question is about static data member vs global variable not static variable vs global variable.
All of us know what static data member and global variables do. How compilers link them, where they get mapped in memory layout, their default values etc. When I think about them I do not have a clear picture of the possible scenarios where we should use static data member instead of global variable.
I thought of one use case where you want to count the number of objects created for a class. You make one static data member and increase in the ctor whenever you create an new object. But at same thought, we could also do the same thing, counting of the created objects, with the global variable as well.
So, it is not clear to me till now that what are the use cases of using static data member vs global variable?
They are in different scopes:
The static data member can have visibility restriction public/protected/private.
The global variable can be modified without restriction
The static (global) variable can only be modified in file scope.

Does a reference singleton go on the stack or the heap?

I've read a lot of articles here about singletons, but none really touch my issue. I understand Singletons should only be use when needed and, in my game, I am using them for specific parts of the engine.
That said, I originally had my singletons as pointers like this:
static MapReader* Instance()
{
if (instance == 0)
{
instance = new MapReader();
return instance;
}
return instance;
}
However I always felt like using too many pointers is bad for leaks and I prefer not using them if I can help it (or smart pointers if I have to). So I've changed all my singletons to references like this:
static MapReader& Instance()
{
static MapReader instance;
return instance;
}
However, now I've notice my game to lag at odd times and then speed up, like the FPS are a little wonky.
My question is that; does the reference singleton all pile up on the stack? or do they still get allocated on the heap? And should I change them back to pointers using smart pointers?
It's almost certainly not on the heap by virtue of the fact it's not created with new.
However, the standard is silent on where static variables are placed, mentioning only their behaviour. See for example, C++11 3.7.1:
1/ All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program (3.6.2, 3.6.3).
2/ If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 12.8.
3/ The keyword static can be used to declare a local variable with static storage duration.
4/ The keyword static applied to a class data member in a class definition gives the data member static storage duration.
That's pretty much the extent of what the standard itself imposes on them.
Most implementations would likely have an area separate from both heap and stack for storing variables of static storage duration.
It's also almost certainly not the use of statics and references that are slowing your code down. Having looked deeply into compilers and how they work, statics tend to be at least as fast as other variables since they're very quick to locate in memory.
As an aside, your pointer variant of the singleton has two issues. The first is a potential race condition if you're working in a threaded environment. There's a possibility that more than one object may be created if distinct threads call Instance().
Specifically, if thread A enters the if statement then thread B starts running, B can go through, create an object then return. If A then continues, it will create a new object.
If you're single-threaded, or you create the instance only from one thread, or you create the instance before other threads are running, you should be fine.
The second issue is just eye candy. There's no need to return the object from within the if block, since it will be returned when you get to the bottom of the function:
static MapReader* Instance() {
if (instance == 0)
instance = new MapReader();
return instance;
}
Neither. Static variables inside functions reside in the data section. For the record, so do static variables outside functions, and global ones.

What does static variable in general mean for various programming language and circumstances?

Static variables are usually: (in most programming languages) shared, persistent, and allocated on the code section of the program
But what does that have anything to do with the word static? What is so static about that? I thought static means doesn't change?
For example, in vb.net static is written shared and that means a member function that can be accessed without object instantiation. Static within function usually means that the variable life time is the life time of the whole program. It seems that static variables are stored on the code section of the computer. Am I correct in my understanding based on the example?
Well, I think the keyword is appropriate. It means the variable you declare as static will remain stored at the same location throughout the whole execution of your program.
I thought static means doesn't change
This corresponds to the const keyword. Const implies it doesn't change, static implies it doesn't "move", as to it stays stored at the same location.
In general, what doesn't change with something that is static in
a programming language is whether it is alive or not. Static
variables are always alive; they have a single instance which
comes into being either at the beginning of the program or the
first time they are visible, and lasts until the end of the
program. Non-static variables come and go, as blocks are
entered and left, or as class instances are created and
destroyed.
In C++, for reasons of C compatibility, static, when applied to
variables at namespace scope, has a completely unrelated
meaning: it means that the variable has internal, rather than
external linkage, and is not visible in other translation units.
Why the word static was adopted for this in early C, I don't
know; I can only guess that they needed something, and didn't
want to introduce a new keyword. (Originally, in the very
earliest versions of C, variables at file scope obeyed the rules
of a Fortran named common block: all variables of the same name
referred to the same storage.) Looking back, of course (with 20/20
hindsight), the default for variables at file scope should have
been internal linkage, with a special keyword (public?) to say
that the variable had external linkage. But this was a lot less
obvious in the early 1970's.
Static is referred to the variable storage. Inside a function call, every variable that you declare is pushed on the stack. Unlike other variables, a static variable isn't pushed on the stack, it's like a global variable, that survives the whole execution of the program, with the difference that is visible only inside the block is declared.
I think you just have to learn the meaning of "static" in computer science, and not relate it to spoken English. Especially as it applies to variables and functions, with slightly different outcomes in C.
The definition of the word from http://dictionary.reference.com/browse/static?s=t
pertaining to or characterized by a fixed or stationary condition.
showing little or no change: a static concept; a static relationship.
A static variable is one that maintains its state even after it goes out of scope as opposed to a non static variable which would be re-initialised every time it came back into scope - so can be thought of in terms of having a "stationary condition" or exhibits "no change"
If you can avoid it, just don't go into static for C++. In any modern language static just means there's only ever one instance and it's never destroyed. That's not too far a stretch from the English meaning, and leads nicely to a discussion of const/final/readonly and what that means.
Static variable means ,there is only one copy of the variable,even if you create multiple instances of the class.That is, all objects of the specified class use the same memory location.Or if you want an example,say , we have two threads .On first thread you create a progressbar and on the second you need to update it.In this case you can define a static variable in your progressbar's class to store the progress and create one instance of the class in each thread.One thread for initialising and in the other you change the value of static variable.Since both use the same copy the progress will be available in the first thread.
So static means something that doesnt change its location on creating a new instance..Or we can say something tha preserves its state ;) Blah blah blah

initialization of the static variables

I've just read that if I want to be sure about the initialization order it will be better to use some function which will turn global variable into local(but still static), my question, do I need to keep some identifier which tells me that my static object has already been created(the identifier inside function which prevent me from the intialization of the static object one more time) or not? cause I can use this function with initialization in different places, thanks in advance for any help
The first question is do your static lifetime objects care about the order they are initialized?
If true the second question is why?
The initialization is only a problem if a global object uses another global object during its initialization (i.e. when the constructor is running). Note: This is horrible proactive and should be avoided (globals should not be used and if they are they should be interdependent).
If they must be linked then they should be related (in which case you could potentially make a new object that includes the two old ones so that you can control their creation more precisely). If that is not possible you just put them in the same compilation unit (read *.cpp file).
As far as the standard is concerned, initialization of a function-scope static variable only happens once:
int *gettheint(bool set_to_four) {
static int foo = 3; // only happens once, ever
if (set_to_four) {
foo = 4; // happens as many times as the function is called with true
}
return &foo;
}
So there's no need for gettheint to check whether foo has already been initialized - the value won't be overwritten with 3 on the second and subsequent calls.
Threads throw a spanner in the works, being outside the scope of the standard. You can check the documentation for your threading implementation, but chances are that the once-onliness of the initialization is not thread-safe in your implementation. That's what pthread_once is for, or equivalent. Alternatively in a multi-threaded program, you could call the function before creating any extra threads.