I need to know the difference,am beginner.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
The above gives output as:
Static variable retains its value while non-static or dynamic variable is initialized to '1' every time the function is called. Hope that helps.
suppose
class A
has static variable x... and not static variable pnow 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 Astatic
namespace scope variables have internal linkage, while non-static
namespace scope variables have external linkage by default! Details: aconst
namespace scope variable has internal linkage by default. That linkage can by changed by keywordextern
.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.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.static
data member of a class has external linkage if the name of the class has external linkage. [$3.5/5]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.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 ofstatic
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.
Static variable retains its value during function calls/loops but local variable doesn't;
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.