what is the difference between static and normal variables in c++? - c++

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.

Related

C++ static variable inside a member static function

In general, I would like to know where a member's static function's local variables are stored? I.e. if a static variable is only used inside a static function, is the variable only initialized once?
Please refer to the code below
std::string const CONST1 = "const1";
std::string const CONST2 = "const2";
std::string const CONST3 = "const3";
class Test
{
public:
static const std::vector<std::string> GetSomeMap();
}
const std::vector<std::string> Test::GetSomeMap()
{
static std::vector<std::string> SomeMap = boost::assign::list_of(CONST1)(CONST2)(CONST3);
return SomeMap;
}
With the above code, is there an advantage to declaring SomeMap as static? (I am expecting it to be only initialized once.)
if a Static variable is used inside a static function is the variable only initialised once ?
The answer is "yes".
It is also "yes" for static variables of regular, i.e. non-static, member functions.
It is also "yes" for static variables of non-member functions.
Static variables inside functions (regardless of the type of function) are stored in the "DATA" segment, just like global variables. So you could say that in this way, function static variables are similar to global ones, just that they are only accessible by name within a limited scope (the function body).
If a variable is static ,it is stored in heap.
If a variable is a member of static function, it is stored in static local variable.
And, they are only initialised once.
In General I would like to ask where a Member Static function's local variables are stored ?
Depends. A static constant plain old datatype may be stored in a read-only data segment. A static variable with constant initializer may be stored in the data segment, and a static variable that requires dynamic initialization may be stored in the BSS segment.
if a Static variable is used inside a static function is the variable only initialised once ?
Yes. In this case, SomeMap will be initialized the first time control passes through its declaration.
The zero-initialization (8.5) of all local objects with static storage duration (3.7.1) is performed before any
other initialization takes place. A local object of POD type (3.9) with static storage duration initialized with
constant-expressions is initialized before its block is first entered. An implementation is permitted to perform
early initialization of other local objects with static storage duration under the same conditions that an
implementation is permitted to statically initialize an object with static storage duration in namespace scope
(3.6.2). Otherwise such an object is initialized the first time control passes through its declaration; such an
object is considered initialized upon the completion of its initialization. If the initialization exits by throwing
an exception, the initialization is not complete, so it will be tried again the next time control enters the
declaration.
Section 6.7, paragraph 4 of ISO/IEC 14882:2003(E) (sorry, I don't have a more recent copy of the standard handy)
From the above code, is there an advantage of declaring SomeMap as static ?( I expect it to be only initialized once )
Yes there is an advantage to declaring it static -- it will only be initialized once and only initialized if it is used. If Test::GetSomeMap is never call, SomeMap is never initialized.
As #Blacktempel states above, however, Test::GetSomeMap should return by reference to remove any doubts about the creation of extra copies SomeMap.
You should also note that you are incurring the cost of the creation of three strings (CONST1, CONST2, and CONST3), each of which may allocate heap memory to store the a copy of their constant-expression character string initializers ("const1", "const2", "const3"). Furthermore, if you call Test::GetSomeMap, you are also incurring the cost of initializing the SomeMap vector which may also allocate heap memory to store the copies of the strings.
If you are concerned about memory usage and initialization overhead and you truly want a static constant array of strings, just declare one, like so:
static const char* const * GetSomeMap(void) {
static const char* const SomeMap[] = {"const1", "const2", "const3"};
return SomeMap;
}
SomeMap will consume a minimum of memory with no initialization overhead (and be completely unchangeable).

const and static keywords are confusing? [duplicate]

Can someone explain the difference between a static and const variable?
A constant value cannot change. A static variable exists to a function, or class, rather than an instance or object.
These two concepts are not mutually exclusive, and can be used together.
The short answer:
A const is a promise that you will not try to modify the value once set.
A static variable means that the object's lifetime is the entire execution of the program and it's value is initialized only once before the program startup. All statics are initialized if you do not explicitly set a value to them.The manner and timing of static initialization is unspecified.
C99 borrowed the use of const from C++. On the other hand, static has been the source of many debates (in both languages) because of its often confusing semantics.
Also, with C++0x until C++11 the use of the static keyword was deprecated for declaring objects in namespace scope. This deprecation was removed in C++11 for various reasons (see here).
The longer answer: More on the keywords than you wanted to know (right from the standards):
C99
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
/* file scope, static storage, internal linkage */
static int i1; // tentative definition, internal linkage
extern int i1; // tentative definition, internal linkage
int i2; // external linkage, automatic duration (effectively lifetime of program)
int *p = (int []){2, 4}; // unnamed array has static storage
/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // static, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"} // static, non-modifiable
void f(int m)
{
static int vla[ m ]; // err
float w[] = { 0.0/0.0 }; // raises an exception
/* block scope, static storage, no-linkage */
static float x = 0.0/0.0; // does not raise an exception
/* ... */
/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // automatic storage, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"} // automatic storage, non-modifiable
}
inline void bar(void)
{
const static int x = 42; // ok
// Note: Since an inline definition is distinct from the
// corresponding external definition and from any other
// corresponding inline definitions in other translation
// units, all corresponding objects with static storage
// duration are also distinct in each of the definitions
static int y = -42; // error, inline function definition
}
// the last declaration also specifies that the argument
// corresponding to a in any call to f must be a non-null
// pointer to the first of at least three arrays of 5 doubles
void f(double a[static 3][5]);
static void g(void); // internal linkage
C++
Has the same semantics mostly except as noted in the short answer. Also, there are no parameter qualifying statics.
extern "C" {
static void f4(); // the name of the function f4 has
// internal linkage (not C language
// linkage) and the function’s type
// has C language linkage.
}
class S {
mutable static int i; // err
mutable static int j; // err
static int k; // ok, all instances share the same member
};
inline void bar(void)
{
const static int x = 42; // ok
static int y = -42; // ok
}
There are a few more nuances of C++'s static that I leave out here. Have a look at a book or the standard.
Static Variables:
Initialized only once.
Static variables are for the class (not per object). i.e memory is allocated only once per class and every instance uses it. So if one object modifies its value then the modified value is visible to other objects as well. ( A simple thought.. To know the number of objects created for a class we can put a static variable and do ++ in constructor)
Value persists between different function calls
Const Variables:
Const variables are a promise that you are not going to change its value anywhere in the program. If you do it, it will complain.
const is equivalent to #define but only for value statements(e.g. #define myvalue = 2). The value declared replaces the name of the variable before compilation.
static is a variable. The value can change, but the variable will persist throughout the execution of the program even if the variable is declared in a function. It is equivalent to a global variable who's usage scope is the scope of the block they have been declared in, but their value's scope is global.
As such, static variables are only initialized once. This is especially important if the variable is declared in a function, since it guarantees the initialization will only take place at the first call to the function.
Another usage of statics involves objects. Declaring a static variable in an object has the effect that this value is the same for all instances of the object. As such, it cannot be called with the object's name, but only with the class's name.
public class Test
{
public static int test;
}
Test myTestObject=new Test();
myTestObject.test=2;//ERROR
Test.test=2;//Correct
In languages like C and C++, it is meaningless to declare static global variables, but they are very useful in functions and classes.
In managed languages, the only way to have the effect of a global variable is to declare it as static.
Constants can't be changed, static variables have more to do with how they are allocated and where they are accessible.
Check out this site.
Static variables are common across all instances of a type.
constant variables are specific to each individual instance of a type but their values are known and fixed at compile time and it cannot be changed at runtime.
unlike constants, static variable values can be changed at runtime.
A static variable can get an initial value only one time. This means that if you have code such as "static int a=0" in a sample function, and this code is executed in a first call of this function, but not executed in a subsequent call of the function; variable (a) will still have its current value (for example, a current value of 5), because the static variable gets an initial value only one time.
A constant variable has its value constant in whole of the code. For example, if you set the constant variable like "const int a=5", then this value for "a" will be constant in whole of your program.
static is a storage specifier.
const is a type qualifier.
Static variables in the context of a class are shared between all instances of a class.
In a function, it remains a persistent variable, so you could for instance count the number of times a function has been called.
When used outside of a function or class, it ensures the variable can only be used by code in that specific file, and nowhere else.
Constant variables however are prevented from changing. A common use of const and static together is within a class definition to provide some sort of constant.
class myClass {
public:
static const int TOTAL_NUMBER = 5;
// some public stuff
private:
// some stuff
};
static means local for compilation unit (i.e. a single C++ source code file), or in other words it means it is not added to a global namespace. you can have multiple static variables in different c++ source code files with the same name and no name conflicts.
const is just constant, meaning can't be modified.
Const means “cannot be changed.”
Static means “static instance (in memory) vs dynamic instance (on the stack.)” Static variables exist for the duration of the program. Dynamic ones are created and destroyed as needed.
A variable can be one or both.
const means constant and their values are defined at compile time rather than explicitly change it during run time also, the value of constant cannot be changed during runtime
However static variables are variables that can be initialised and changed at run time. However, static are different from the variables in the sense that static variables retain their values for the whole of the program ie their lifetime is of the program or until the memory is de allocated by the program by using dynamic allocation method. However, even though they retain their values for the whole lifetime of the program they are inaccessible outside the code block they are in
For more info on static variables refer here
Constant variables cannot be changed. Static variable are private to the file and only accessible within the program code and not to anyone else.
static keyword defines the scope of variables whereas const keyword defines the value of variable that can't be changed during program execution
Simple and short answer is memory is allocated for static and const only once. But in const that is for only one value where as in static values may change but the memory area remains the same until the end of the program.
static value may exists into a function and can be used in different forms and can have different value in the program.
Also during program after increment of decrement their value may change but const in constant during the whole program.

Variables auto-initialized to 0 in unnamed namespace?

My understanding is that static variables get put in the uninitialized variable section of the binary (the BSS section) and so those are safe to assume as being initialized to 0.
But I have a function defined in an unnamed namespace. Inside the function, there is a char array declared without being explicitly initialized to 0. Will this be auto-initialized to 0? What about variables not declared as static but defined in an unnamed namespace? And what about local variables of static functions?
A function local variable will not be automatically initialized to zero, regardless of whether the function is in an anonymous namespace, static, or whatever. This is because the local variables inside a function are not static variables. To cause a local variable to have static storage duration you must explicitly mark it with static.
int foo; // static storage duration (because it's global) automatically zero-initialized
static int foo2; // static storage duration (because it's global) automatically zero-initialized. The static keyword just gives the name 'foo2' internal linkage and has nothing to do with static storage duration.
namespace {
int foo; // static storage duration, automatically zero-initialized
void bar() {
int f; // local variable, not automatically zero-initialized
static int g; // static storage duration (because of the keyword static), automatically zero-initialized
}
}
Don't ever rely on something being initialized/done for you. Just do the initialization always as things may change and you will be caught unaware.
You can't rely on a variable being automatically initialized to any value. Even if this happens constantly in some cases, just changing the compiler could produce totally different results. Safest is to always initialize every variable to be sure of its value. You should also initialize static variables. The fact that a variable belongs to a namespaces does not matter.

static var in member function

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.

What is the difference between a static and const variable?

Can someone explain the difference between a static and const variable?
A constant value cannot change. A static variable exists to a function, or class, rather than an instance or object.
These two concepts are not mutually exclusive, and can be used together.
The short answer:
A const is a promise that you will not try to modify the value once set.
A static variable means that the object's lifetime is the entire execution of the program and it's value is initialized only once before the program startup. All statics are initialized if you do not explicitly set a value to them.The manner and timing of static initialization is unspecified.
C99 borrowed the use of const from C++. On the other hand, static has been the source of many debates (in both languages) because of its often confusing semantics.
Also, with C++0x until C++11 the use of the static keyword was deprecated for declaring objects in namespace scope. This deprecation was removed in C++11 for various reasons (see here).
The longer answer: More on the keywords than you wanted to know (right from the standards):
C99
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
/* file scope, static storage, internal linkage */
static int i1; // tentative definition, internal linkage
extern int i1; // tentative definition, internal linkage
int i2; // external linkage, automatic duration (effectively lifetime of program)
int *p = (int []){2, 4}; // unnamed array has static storage
/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // static, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"} // static, non-modifiable
void f(int m)
{
static int vla[ m ]; // err
float w[] = { 0.0/0.0 }; // raises an exception
/* block scope, static storage, no-linkage */
static float x = 0.0/0.0; // does not raise an exception
/* ... */
/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // automatic storage, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"} // automatic storage, non-modifiable
}
inline void bar(void)
{
const static int x = 42; // ok
// Note: Since an inline definition is distinct from the
// corresponding external definition and from any other
// corresponding inline definitions in other translation
// units, all corresponding objects with static storage
// duration are also distinct in each of the definitions
static int y = -42; // error, inline function definition
}
// the last declaration also specifies that the argument
// corresponding to a in any call to f must be a non-null
// pointer to the first of at least three arrays of 5 doubles
void f(double a[static 3][5]);
static void g(void); // internal linkage
C++
Has the same semantics mostly except as noted in the short answer. Also, there are no parameter qualifying statics.
extern "C" {
static void f4(); // the name of the function f4 has
// internal linkage (not C language
// linkage) and the function’s type
// has C language linkage.
}
class S {
mutable static int i; // err
mutable static int j; // err
static int k; // ok, all instances share the same member
};
inline void bar(void)
{
const static int x = 42; // ok
static int y = -42; // ok
}
There are a few more nuances of C++'s static that I leave out here. Have a look at a book or the standard.
Static Variables:
Initialized only once.
Static variables are for the class (not per object). i.e memory is allocated only once per class and every instance uses it. So if one object modifies its value then the modified value is visible to other objects as well. ( A simple thought.. To know the number of objects created for a class we can put a static variable and do ++ in constructor)
Value persists between different function calls
Const Variables:
Const variables are a promise that you are not going to change its value anywhere in the program. If you do it, it will complain.
const is equivalent to #define but only for value statements(e.g. #define myvalue = 2). The value declared replaces the name of the variable before compilation.
static is a variable. The value can change, but the variable will persist throughout the execution of the program even if the variable is declared in a function. It is equivalent to a global variable who's usage scope is the scope of the block they have been declared in, but their value's scope is global.
As such, static variables are only initialized once. This is especially important if the variable is declared in a function, since it guarantees the initialization will only take place at the first call to the function.
Another usage of statics involves objects. Declaring a static variable in an object has the effect that this value is the same for all instances of the object. As such, it cannot be called with the object's name, but only with the class's name.
public class Test
{
public static int test;
}
Test myTestObject=new Test();
myTestObject.test=2;//ERROR
Test.test=2;//Correct
In languages like C and C++, it is meaningless to declare static global variables, but they are very useful in functions and classes.
In managed languages, the only way to have the effect of a global variable is to declare it as static.
Constants can't be changed, static variables have more to do with how they are allocated and where they are accessible.
Check out this site.
Static variables are common across all instances of a type.
constant variables are specific to each individual instance of a type but their values are known and fixed at compile time and it cannot be changed at runtime.
unlike constants, static variable values can be changed at runtime.
A static variable can get an initial value only one time. This means that if you have code such as "static int a=0" in a sample function, and this code is executed in a first call of this function, but not executed in a subsequent call of the function; variable (a) will still have its current value (for example, a current value of 5), because the static variable gets an initial value only one time.
A constant variable has its value constant in whole of the code. For example, if you set the constant variable like "const int a=5", then this value for "a" will be constant in whole of your program.
static is a storage specifier.
const is a type qualifier.
Static variables in the context of a class are shared between all instances of a class.
In a function, it remains a persistent variable, so you could for instance count the number of times a function has been called.
When used outside of a function or class, it ensures the variable can only be used by code in that specific file, and nowhere else.
Constant variables however are prevented from changing. A common use of const and static together is within a class definition to provide some sort of constant.
class myClass {
public:
static const int TOTAL_NUMBER = 5;
// some public stuff
private:
// some stuff
};
static means local for compilation unit (i.e. a single C++ source code file), or in other words it means it is not added to a global namespace. you can have multiple static variables in different c++ source code files with the same name and no name conflicts.
const is just constant, meaning can't be modified.
Const means “cannot be changed.”
Static means “static instance (in memory) vs dynamic instance (on the stack.)” Static variables exist for the duration of the program. Dynamic ones are created and destroyed as needed.
A variable can be one or both.
const means constant and their values are defined at compile time rather than explicitly change it during run time also, the value of constant cannot be changed during runtime
However static variables are variables that can be initialised and changed at run time. However, static are different from the variables in the sense that static variables retain their values for the whole of the program ie their lifetime is of the program or until the memory is de allocated by the program by using dynamic allocation method. However, even though they retain their values for the whole lifetime of the program they are inaccessible outside the code block they are in
For more info on static variables refer here
Constant variables cannot be changed. Static variable are private to the file and only accessible within the program code and not to anyone else.
static keyword defines the scope of variables whereas const keyword defines the value of variable that can't be changed during program execution
Simple and short answer is memory is allocated for static and const only once. But in const that is for only one value where as in static values may change but the memory area remains the same until the end of the program.
static value may exists into a function and can be used in different forms and can have different value in the program.
Also during program after increment of decrement their value may change but const in constant during the whole program.