Static variables in C++ exist for the lifetime of the entire program rather than individual function calls. They can be declared at global, file, class, or function scope. Globally scoped static variables are initialized when the program starts and exist until it ends, while static variables within functions are initialized on first use and persist between function calls. Static class members belong to the class itself rather than individual objects and can be accessed without an instance.
Introduction to ArtificiaI Intelligence in Higher Education
Ā
Static keyword u.s ass.(2)
1. StaticKeyword
1
Static keyword
We have been using static keyword in our examples. What is the meaning of
static? The word refers to something that is stationary, stopped and not moveable.
What are the types of these variables, declared as static?
How can we make use of them? Static as the word implies are variables which
exist for a certain amount of time, much longer than that by ordinary automatic
variables. Letās consider the example about the lifetime of data variables.
One of the variable types is global variable. Global variables are those that are
defined outside of main. They are written as standalone statements before main
function
int i; the variable āIā is a global variable. It is not only accessible in main but also
in all the functions. They can assign some value to āIā or obtain the value of āIā.
Global variables come into existence whenever we execute the program and the
memory is allocated for āIā. It exists all the time when the program is running. At
the end of the program execution, the memory will be de-allocated and returned to
the operating system. So it has a very long lifetime. We need a value which exists
for the complete execution of the program and is available in all the functions. We
use global variables. It is not a good idea to do that unless it is absolutely
necessary. The major plus point of these variables is that these are accessible from
everywhere in the program. The inconvenience is that these variables are visible in
those functions too which does not need them
The Many Meanings of the C++ āStaticā Keyword
In C++, the static keyword has a lot of meanings. Letās go over all of them
Meaning 1: Private Linkage
This one comes from C, and it lets you mark a variable as āfile privateā.
2. StaticKeyword
2
Example:
static int i = 42;
void doSomething()
{
cout << i;
}
In this example, static tells the compiler to not make the variable i available from
other sourcefiles. If another file tries to use i, perhaps using the extern keyword, it
would generate a linker error (unresolved external symbol). The same concept
applies to functions whose access you want to limit to the current file.
Uses:
This is very handy for creating āfile privateā variables and functions. I recommend
using static for any file-only functions. This way, you can name them whatever
you like without risking a naming collision in the global namespace.
Gotchas:
Unfortunately, you canāt declare a class as static. Also, the language makes no
guarantee about the order in which static variables are initialized. In my
experience, static variables in the same file are initialized in a āsaneā order, so you
can do things like this
static int i = 42;
static int j = i + 1;
Meaning 2: Function Call Spanning
This one also comes from C, and it lets you give a function-local variable a long
lifespan.
Example:
void foo()
3. StaticKeyword
3
{
static int callCount = 0;
callCount++;
cout << "foo has been called " << callCount << " times" << endl;
}
Uses:
itās a great way to keep track of how many times a function has been called, so it
works well for generating unique ID numbers (watch out for thread-safety!). Itās
also useful to keep track of whether a function is being called for the first time
ever, like this:
void foo()
{
static boolfirstTime = true;
if(firstTime)
{
// Do something special here
firstTime = false;
}
}
Gotchas:
Static function-local variables are initialized the first time the function is called,
not before. Using these kinds of variables can often make your codenot thread safe
and not re-entrant, so take care before using them. You can put static variables
within scopeblocks (like inside an if or for statement). Iām not totally sure what
4. StaticKeyword
4
the implications are, and frankly Iāve never felt the need to limit the scopeof a
variable so aggressively.
Meaning 3: Per-Class Data
When you declare a class member as static, it now belongs to the class at large, and
not a particular instance.
Example:
// In the .h file:
class MyClass
{
public:
static int FavoriteNumber;
static void foo();
};
// In the .cpp file (to initialize the static variable):
int MyClass::FavoriteNumber = 42;
void MyClass::foo()
{
// can't access member variables here!
}
Uses:
5. StaticKeyword
5
Itās very common to store class-level constants this way. You can declare class
functions as static as well, so they would be callable from anyone who has access
to your class, even if they donāthave an instance. This is handy for helper
functions. I generally like to make class functions static if they donātneed to
operate on any instance data, typically for private helper functions.
Gotchas:
Static members are initialized very early in your programās execution, before
main() is even called actually. You also have no guarantee about the order in
which they are initialized between classes in different files. Be careful not to
initialize one static class variable from another (possibly not-yet-initialized) static
class variable. Also, you canāt access instance data from this within a static class
function (unless someone passes you a this pointer). Lastly, you have to initialize
your static class variables in your implementation (.cpp)file. Otherwise, the
compiler doesnātknow how to allocate them (see the example above).
What is the difference between a static class and a static
member variable or method?
Let's start with the memory first. Whenever a process is loaded in the RAM, we
can say that the memory is roughly divided into three areas (within that process):
Stack, Heap, and Static (which, in .NET, is actually a special area inside Heap
only known as High FrequencyHeap).
The static part holds the āstaticā member variables and methods. What exactly is
static? Those methods and variables which don'tneed an instance of a class to be
created are defined as being static. In C# (and Java too), we use the static keyword
to label such members as static. For e.g.
class MyClass
{
public static int a;
public static void DoSomething();
}
6. StaticKeyword
6
These member variables and methods can be called without creating an instance of
the enclosing class. E.g., we can call the static method DoSomething( ) as:
MyClass.DoSomething();
We don't need to create an instance to use this static method.
Static class declarations
The static keyword in C++ is used to specify that variables will be in
memory till the time the program ends; and initialized only once. Just
like C# and Java, these variables donāt need an object to be declared to
use them.
Summary
Static methods in the C# language differ from instance methods in
both the method declarations and in the method call sites. Static
methods apply to a type, not an instance of the type they are
defined on