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.
Related
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.
This question already has answers here:
Unnecessary curly braces in C++
(14 answers)
Closed 9 years ago.
I came across one project,where I found some code which I is not understandable to me. I just started with C++, so it seems like a big problem for me. I am providing few lines of my project,which I am not able to understand.
class abc
{
public:
//some stuff
abc();
};
abc::abc()
{
int someflag = 0;
//code
if(someflag == 0)
{
do
{
//few strcpy operations
{ //(My Question)Without any condition braces started
//variable initialization
}
}while(condition);
}
}
Now my questions...
What we can achieve by doing this operation?
What is happening in inside braces of do-while loop?
What is the scope of the initialized variables (I mentioned) inside
do-while loop?
Is it C++11?
Help me to understand this.
What we can achieve by doing this operation?
You introduce a scope block for the variables inside.
What is happening in inside braces of do-while loop?
See above.
What is the scope of the initialized variables (I mentioned) inside do-while loop?
The variables go out of scope at the end of the braces, they're there for that sole reason. One use case I can think of for this is a scoped_lock or something similar to it for multi-threaded applications.
Is it C++11?
No.
Even in C you can open a brace in any point where a statement is permitted.
This allows to declare and use new variables without interferring with the enclosing scope. For example:
... code before ...
{
int i = 0, sum = 0;
while (i < n) {
sum += dothis(data[i++]);
}
dothat(sum);
}
... code after ...
the two variables i and sum have nothing to do with variables with the same name in the enclosing scope: these two variables are created when entering the block and destroyed when exiting the block (while instead n and data are defined outside). This can help readability by avoiding separation between declaration and use or between declaration and initialization (in old C you were not allowed to put a variable declaration right before use... all locals were required to be declared at start of function: an annoying problem if you don't know yet the value to give them).
If you are in C++ and these block-local variables have a class type the constructor is called when entering the block (not when entering the function) and destroyed immediately when exiting the block. This can be very useful for example for locks
{
Lock mylock(resource);
use_resource();
}
Here are your answers:
Ans 1,2. This is used to define a new scope.
Ans 3. The scope of variables end as soon as the control moves out of the block
Ans 4. Probably the coder comes from C background and it is not particular to C++11 as in C, variables can only be declared at the beginning of a new scope.
Please look at THIS and THIS for further reference.
There are five types of scopes in C++
Function
File
Block
Function Prototype
Class
The code which you shared shows 'block scope'
Block scope
Blocks are portions of C++ code contained within curly braces( {....} ). Identifiers declared within a block have block scope and are visible from their points of definition to the end of the innermost containing block. A duplicate identifier name in a block hides the value of an identifier with the same name defined outside the block.
A variable name declared in a block is local to that block. It can be used only in it and the other blocks contained under it.
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.
bool SomeClass::Function( bool thankYou = true )
{
static bool justAbool = false;
// Do something with justAbool;
...
}
I have searched around but I can't find anything about this except globals vars or member functions itself.
What does the above do, i.e. what happens, does justAbool keep its value after leaving the scope? Or does it 'remember' the value when it re-enters the scope?
The variable justAbool is initialized to false only once and it is initialized before the function is entered. The value will be remembered after leaving the scope of the function. It is important to note that the value will also be shared by all instances of SomeClass just like a static member variable. The variable justAbool will not be re-initialized if you create a new instance of your class and then call the function again.
static when applied to a local variable gives that variable static storage duration. This means that the justAbool's lifetime lasts to the end of the program rather than to the end of the invocation of the function. It's scope stays the same, it can only be accessed by name in the function, after the declaration appears.
justAbool will be initialized (using the supplied initializer = false) the first time that the function is called. Thereafter it will retain its previous value, it will not be reinitialized when the function is called again.
Here are some fuller details about storage duration and lifetimes, with references to the standard.
If an object has static storage duration, it means that the storage for the object lasts for the duration of the program (beginning to end). (3.7.1 [basic.stc.static])
As a bool is a type without a non-trivial constructor, its lifetime mirrors that of its storage, i.e. it lives from the beginning to the end of the program. (3.8 [basic.life])
All objects with static storage duration (including local objects) are zero-initialized before any other initialization. (6.7/4 [stmt.decl]) [For local objects with an initializer this is fairly academic because there is no way to read their value before their declaration is reached.]
Local objects of POD type with static storage duration initialized with constant-expressions are initialized before their block is entered, otherwise local objects with static storage duration are initialized when control passes through their declaration. (6.7/4 again)
An implementation is permitter, but not required, to perform early initialization in some situations.
The above function does what it does in the comment // Do something with justAbool;.
On a serious note, yes, the static variable (in this case justAbool) inside a function retains it's value even after returning from the function. It gets initialized ONLY ONCE. And each successive calls uses it as if it's a global variable. Its life-time is equal to the end of the program.
int f()
{
static int v = 0;
return ++v;
}
int main()
{
cout << f() << endl;
cout << f() << endl;
cout << f() << endl;
cout << f() << endl;
}
Output:
1
2
3
4
Online Demo : http://www.ideone.com/rvgB5
The justAbool is actually a regular static variable - it exists from the start of the program and is initialized only once. The special thing is that is is known only in this function - if you try and use it outside the function the compiler won't know what it is.
justAbool keeps its value after leaving the scope. What else did you want this code to do exactly?
function level static local variable, the initialization depends on variable types:
POD: initialized before main()
non-POD: initialized the first time, the line in the function is executed.
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.