MyClass GlobalVar;
int main()
{
MyClass VarInMain;
}
A couple of things:
Typically, they're allocated in different places. Local variables are allocated on the stack, global variables are allocated elsewhere.
Local variables in main are only visible within main. On the other hand, a global variable may be accessed anywhere.
More differences:
If constructor/destructor of global object throws an exception, then function terminate is called and there is no chance to proceed. For local object, you can catch exception and do something (but it is still tricky to throw from destructor).
Order of construction/destruction of global objects is not well specified. This means, that generally for two global objects you cannot say, which one is constructed first. From the other hand, local objects are created at point of defintion and destructed at end of block in order reverse to order of creation.
Scope... (already mentioned)
In general, it is not a good practice to use global objects without very strong reasons to do so. Using of globals often leads to code which is hard to maintain.
The variable VarInMain is a local variable and can only be used inside the function where it is declared, in your case, the main function. The GlobalVar can be used in every function of your program because it was declared outside of a function. This is called Scope.
Scope. VarInMain can be accessed directly only by code in main. GlobalVar can be accessed directly by code in any function in the file.
A simple example:
int y = 43;
void foo() {
// y is visible here, x is not
}
int main() {
int x = 42;
foo(); // x is visible here, but not when we enter the foo() function
}
A global variable is visible globally, across all functions.
A local variable is visible in the scope in which it is declared only. if you declare a local variable inside main, it will be visible there, yes, but not in functions that are called from main.
VarInMain is accessible only within the main() function. If main() calls another function, that function will not have access to it. This is function scope.
GlobalVar is accessible in every function in the same file. If you put extern MyClass GlobalVar; in a header, then it can be used in any function in files which have or include that declaration. This is global scope.
Another difference: the order of global object initilization is undefined.
For example:
static Integer Global_Integer(5);
static Foo Global_Foo;
As these are objects, the C++ runtime will call their constructors when initializing them, but we can't predict the order in which this will happen.
Another difference:
Global variables will be initialized before the program starts (i.e. main() gets called) whereas the local variables are initialized as execution reaches that point (i.e. just after main is called in the above example).
globals can be used in functions declared outside of main, while anything declared in main, must be passed to another function first.
Another one: The global variables (or variables in any other namespaces) are initialized to (T)0, with T being the type of the variable (in case it's a simple non-class type), arrays and classes are initialized like that for all their elements.
But in my opinion, it's a good idea to explicitly initialize things anyway, and not rely on that zero initialization since it improves readability of the program when the initial value is explicitly mentioned. It's however still useful to know when reading someone else's code, always keeping in mind the compiler will initialize those automatically.
The local variable when it is not declared static isn't automatically initialized. So you have to do any initialization on your own in case T has no constructor doing it for you. Always keep that in mind.
A global variable is accessible to any function. A variable in main acts exactly like any other local variable, and is only accessible to code in main.
Also, if main (or another function) calls itself, the local variables will be copied, but global variables will not.
int x = 0;
void myfunction()
{
x++;
printf("%i ",x);
}
int main()
{
myfunction();
myfunction();
}
This example will output:
1
2
Moving the "int x = 0;" into myfunction will output:
1
1
Because the local variable gets initialised each time myfunction is called.
LOCAL VARIABLE
It is a variable which is declared within a function or within a block. It is accessible only within a function/block in which it is declared.
GLOBAL VARIABLE
It is a variable declared outside all the functions. It is accessible throughout the program.
Related
If I write something like this:
#include <iostream>
int main()
{
using namespace std;
{int n;n=5;} cout<<n;
system("pause");
return 0;
}
The compiler tells me that n is undeclared. Then I tried making it static, but again, the compiler tells me that it is undeclared. Doesn't a variable declated static have program scope? If not, how do I use n in this program?
You're confusing scope with lifetime. Static variables have a lifetime equal to the program's lifetime, but they still follow scoping rules based on where they are declared.
The scope of n is just between the brackets:
{int n;n=5;}
so outside of the block, you have no n variable.
Making it static just makes it's value retain even after you exit the block so that the next time you enter that block again, you can retrieve it's value from the last time you executed that block, but still it's scope is still within the brackets.
A variable declared static in the global scope has its scope limited to the translation unit. A variable declared static within a function has its lifetime set to be the same as the program's, but in this case does not affect its scope. You will have to put cout in the same scope as n was declared in order to use it.
Here the compiler gives error n is undeclared because here "{int n;n=5;}" it is declared in the braces. And braces tells us about the scope of the variable. When ever the scope ends the variable is deleted from the memory.
And for Static and local.
Static : The variable is same like global variable but its value remains constant throughout the application. And the static variable cannot be used on the other page using extern.
Local : The local variables are stored in the stack and they are deleted when they get out of scope.
how do I use n in this program?
using namespace std;
int main()
{
int n; // declare n as int
n=5; // assign it a value
cout << n; // display it.
system("pause");
return 0;
}
Please don't be confuse between scope and life time of a static variable. Scope means where can you access the variable. Life time of variable is duration for which variable stay in memory. In your case,
Scope of x varible is within the curly braces. Life time of x would be program scope.
int main()
{
int x;
int x;
return 0;
}
This snippet will give an error:
error: redeclaration of 'int x'
But this one, works just fine:
int main()
{
while(true)
{
int x;
{...}
}
return 0;
}
Which is the reason why in the second example, declaring x in the loop does not redeclare it every iteration? I was expecting the same error as in the first case.
You're smashing together two related but different concepts and thus your confusion. But it's not your fault, as most of the didactic material on the matter doesn't necessarily make the distinction between the two concepts clear.
Variable scope: This is the region of the source code where a symbol (a variable) is visible.
Object lifetime: this is the time during the runtime of the program that an object exists.
This brings us to other two concepts we need to understand and differentiate between:
A variable is a compile-time concept: it is a name (a symbol) that refers to objects
An object is an "entity" at runtime, an instance of a type.
Let's go back to your examples:
int main()
{
int x{};
int x{};
}
Here you try to declare 2 different variables inside the same scope. Those two variables would have the same name inside the function scope, so when you would "say" the name x (when you would write the symbol x) you wouldn't know to which variable you would refer. So it is not allowed.
int main()
{
while(true)
{
int x{};
}
}
Here you declare one variable inside the while body scope. When you write x inside this scope you refer to this variable. No ambiguity. No problems. Valid code. Note this discussion about declarations and variable scope applies at compile-time, i.e. we are discussion about what meaning has the code that you write.
When we discus object lifetime however we are talking about runtime, i.e. the moment when your compiled binary runs. Yes, at runtime, multiple objects will be created and destroyed in succession. All of these objects are referred by the symbol x inside the while body-scope. But the lifetimes of these objects don't overlap. I.e. when you run your program the first object is created. In the source code it is named x inside the while-body scope. Then the object is destroyed, the loop is re-entered and a new object is created. It is also named x in the source code inside the while-body scope. Then it is destroyed, the while is re-entered, a new object is created and so on.
To give you an expanded view on the matter, consider you can have:
A variable which never refers to an object
{ // not global scope
int a; // <-- not initialized
}
The variable a is not initialized, so an object will never be created at runtime.
An object without a name:
int get_int();
{
int sum = get_int() + get_int();
}
There are two objects returned by the two calls to the function get_int(). Those objects are temporaries. They are never named.
Multiple objects instantiated inside the scope of a variable.
This is an advanced, contrived example, at the fringe of C++. Just showing that it is technically possible:
{
int x;
// no object
new (&x) int{11}; // <-- 1st object created. It is is named `x`. Start of its lifetime
// 1st object is alive. Named x
x.~int(); // <-- 1st object destructed. End of its lifetime
// no object
new (&x) int{24}; // <-- 2nd object created. Also named `x`
// 2nd object alive. Named x
} // <-- implicit end of the lifetime of 2nd object.
The scope of x is the whole block delimited by the curly brackets. However there are two object with different non-overlapping lifetimes inside this scope.
Declarations don't happen at runtime, they happen at compile-time.
In your code int x; is declared once, because it appears in the code once. It doesn't matter if it's in a loop or not.
If the loop runs more than once, x will be created and then destroyed more than once. It's allowed, of course.
In c++, the curly braces represent the beginning {, and end }, of a scope. If you have a scope nested inside another scope, for example a while loop inside a function, then the previously declared variables from the outer scope are available inside the new loop scope.
You are not allowed to declare a variable with the same name inside the same scope twice. That's why the compiler creates the first error
error: redeclaration of 'int x'
But in the case of the loop, the variable is only declared once. It doesn't matter that the loop will reuse that declaration multiple times. Just like a function being called multiple times doesn't create a redeclaration error for the variables it declares.
Variables in loops stay in loops, and are not redeclared. This is because, to the best of my knowledge, Loops are just sets of instructions with jump points, and not actually the same code in the .exe file written over and over again.
If you try to make a for loop:
for(int x = 0; x < 10000; ++x);
The loop just reuses the same variable, then removes the variable after use. This is helpful so that loops, and do{}while(condition)'s can actally hold values, and not just have to redeclare, and reset each variable.
Back to the original question, I am going to ask my own: Why are you trying to redeclare a variable? You could just do this:
int main(void){
int variable = 0;
...
variable = 2;
}
Instead of this:
int main(void){
int variable = 0;
...
int variable = 2;
}
Curly brackets in C/C++ represent blocks of code. These blocks of code do not transfer information to other blocks. I recommend looking further into resources on blocks of code, but one resource has been linked here.
Unlike code that is written in "interpreted languages", variables require declaration. Moreover, your code is read sequentially in compiled languages.
Block example:
while (true) {
int i = 0;
}
This declaration is stored with the block somewhere in memory.
The storage is assigned to an "int" variable type. This data member has a certain memory capacity. Redeclaring, in essence, tries to override information stored in that particular block. These blocks are set aside at compilation time.
Returning a reference from a static like shown here is legal C++
static int& from_static() {
static int x;
return x;
}
Everything looks swell so far. But would it also be legal, if the static variable inside the function was thread_local instead?
static int& from_thread_local() {
thread_local int x;
return x;
}
Actually, I'm pretty sure it is. But mixing the static keyword in the declaration of the function with the thread_local from the variable declaration somehow doesn't sparkle with me.
This depends on how you are using it. thread_local storage duration lasts for the life time of the thread that created the variable. So, if this function was called by a thread then x would live until that thread exited. If you ran from_thread_local in it's own thread then it would not be safe as you wouldn't get the value until after the thread ends and the lifetime of x has ended.
The static on the function level has no effect on this since in that context static describes the linkage of the function, not the duration when it is a free function. If it is a member function then it just describes that no instance of the class is needed to call the function.
You are basically asking two questions:
Is it ok to return a reference to a local thread_local variable?
What happens when you return a reference to a local thread_local variable from a static function?
The answer to question 1 is yes. The variable will outlive the function call, so the reference will be usable. (However, there are some obvious cases where this is not true, e.g., do not use the return value from such a function if you are wrapping it in a packaged_task that you are going to execute in another thread.)
The answer to question 2 is: the fact that the function is static has no effect on the meaning of the thread_local local variable. In the case of the Meyers singleton, the static specifier just means the function doesn't require an instance of the enclosing class.
Yes it is still legal C++.
However keep in mind that the reference you're returning is to a variable that is local to the thread, not to the function. So you need to take care not to exchange the reference between threads, or if you do you must ensure not to use it after the originating thread exits.
I have a global variable inside an anonymous namespace.
namespace {
std::unordered_map<std::string, std::string> m;
}
A::A() { m.insert(make_pair("1", "2")); } // crasches
void A::insert() { m.insert(make_pair("1", "2")); } // ok
If try to use the map inside the constructor I get Access violation reading location.
But if I use it after A has been initialized it works.Is this behavior correct?
What is the scope of the A object whose constructor invocation is causing the crash?
There are no guarantees as to the order that static initializers are executed, so that if your A object is also a global or static (as m is), it's quite possible that m does not exist yet in terms of being a validly constructed object, which would mean that your call to std::unordered_map::insert() would be invoked on uninitialized memory, thus leading to your crash.
A solution is to make sure that all of your A instances that depend on m are constructed explicitly by you and not statically/globally (or as the commenter added, if they are in the same TU, to order them properly), or to change the structure of A such that you can call a function on an instance later in order to do the insert. Whether or not this is a valid solution depends more on the overarching usage of A.
You are probably creating a class of type A in a static context somewhere in your application, ie before your main() function is executed, and therefore before m has been initialized.
I need to know the difference,am beginner.
void func()
{
static int static_var=1;
int non_static_var=1;
static_var++;
non_static_var++;
cout<<"Static="<<static_var;
cout<<"NonStatic="<<non_static_var;
}
void main()
{
clrscr();
int i;
for (i=0;i<5;i++)
{
func();
}
getch();
}
The above gives output as:
Static=2
Nonstatic=2
Static=3
Nonstatic=2
Static=4
Nonstatic=2
Static=5
Nonstatic=2
Static=6
Nonstatic=2
Static variable retains its value while non-static or dynamic variable is initialized to '1' every time the function is called. Hope that helps.
A static variable is a single memory location associated with the class.
A non-static variable (that is a member of a class) represents a different memory location for each instance of the class.
Static variables can be initialized only once and assign to 0 when an object is created.
static namespace scope variables have internal linkage, while non-static namespace scope variables have external linkage by default! Details: a const namespace scope variable has internal linkage by default. That linkage can by changed by keyword extern.
static variables in a class is associated with the class, that means, all instances of the class have the same instances of the static variables; they’re like a global variables that every instance of the same class has access to.
non-static variables in a class are instance members, that is, every instance of the class will have its own instances of the non-static variables.
a static data member of a class has external linkage if the name of the class has external linkage. [$3.5/5]
a static variable inside a function retains its value even after returning from the function.
That is, its lifetime is equal to the lifetime of the program itself. This is demonstrated in Mahesh's answer.
Main difference in static and normal variable is in their lifetime, for example scope and lifetime of local variable is within the function-loop in which it is declared, but scope of static variable is same as local variable means it will be accessed within which function it is declared(if not defined globally), but lifetime is through the program. So memory allocation depends on the lifetime, so as static variable will not die till program terminates so no new memory allocated, so fixed memory address allocated to static variables and value in that address will be overwritten every time we change the value of variable, while for normal variable as soon as you will go out of scope, variable will die(means memory will be freed for that variable) and when you will define variable again new memory address will be assigned, new value will be stored in address and no concept of overwrite(when we go out of scope).
Static variable retains its value during function calls/loops but local variable doesn't;
#include <iostream>
void foo()
{
for( int i=0; i<5; ++i )
{
static int staticVariable = 0;
int local = 0;
++local;
++staticVariable;
cout << local << "\t" << staticVariable << "\n";
}
}
int main()
{
foo();
return 0;
}
Results:
1 1
1 2
1 3
1 4
1 5
When a static variable is a member of a class, each instance share the static variable. Each instance doesn't have it's own copy.
class foo
{
public:
static int staticVariable;
};
int foo::staticVariable = 0;
foo obj1, obj2 ; // Both the instances share the static variable.
Static members are members that are single shared member common to all the objects created for a particular class but non-static are not so.
Memory allocation is done only once and not every time an object is created like non-static members.
Only one copy of static data member will exist irrespective of the number of objects created.
Static member functions can access only static member variables while a non-static member can be accessed by both static and non-static member functions.
Static members are efficient when single copy of data is enough.
Apart from differences in all these answers, there is one more difference between static and local variables:
local variables are stored on the stack, while static variables are stored in the data section of a process memory.
suppose class A has static variable x... and not static variable p
now if you create hundred instance of class A (i.e A a;) x would be shared among this hundred instance... but there would be hundred copies of p... one copy of p per instance of A
There are three different types of "static" variables.
Outside functions and classes, a "normal" variable would be a global variable. A static variable outside a function is not global, but local to the .cpp file in which it's defined. (Don't define this type of static variables in header files!)
Inside a function, a normal variable is destroyed when the function exits. A static variable in a function retains its value even after the function exits.
Inside a class, a normal member belongs to an object. A static member is shared between all objects of that type, and even exists before any object of that class is created.
The main Difference between "Static Variable" and the "Local variable"
The memory allocation of the local variable is deallocated if their work is done,
on other hand, the Memory allocation for the static variable remains the same
until the program terminates or overwritten by the another value of the program.
For example, Suppose You are using a recursion problem, If you are using the local variable during the recursive call, the memory allocation of the Local variable is removed, during the returning of the function.
On the other hand, if you are using the static variable, the memory allocation of that variable will remain until the program ends. It shall intact its values during the returning of the function, or can be overwritten by the programe.