Understanding the static and const Keywords in C/C++
static
The static keyword, when used to declare a varible, places that variable in the global (static) storage area. Initialized and uninitialized static variables are stored in separate regions within this area. If a static variable is not explicitly initialized, it is automatically initialized to 0.
For Local Variables
staticextends the lifetime of a local variable. It is not destroyed when the function exits; rather, it persists until the program terminates.- A static local variable is initialized only once, when the function is first called. Subsequent calls do not reinitialize it—the initialization code is skipped.
- Static local variables retain their value between function calls. The result from the previous call is preserved and used as the initial value for the next call.
- Compared to global variables, static local variables are easier to maintain because they remain within the function's sccope (local scope), making them accessible only from within that function.
For Global Variables
staticchanges the linkage of a global variable to internal linkage. This means the variable is accessible only within the file where it is declared. It cannot be accessed from other files usingexterndeclarations. To use such a variable in an external file, one effectively needs to include the entire source file that contains thestaticglobal variable definition—equivalent to rewriting the file's contents in the external file.- The purpose of
staticfor global variables is to prevent name conflicts. Different files can define global variables with the same name without causing linkage errors, as each is confined to its own translation unit.
For Functions
The behavior of static for functions is identical to that for global variables: it gives the function internal linkage, limiting its visibility to the file in which it is defined.
Supplementary Knowledge: Memory Layout
- Stack Area: Memory allocated and deallocated automatically by the compiler (e.g., local variables, function parameters). Space is released when the scope exits.
- Heap Area: Memory allocated and deallocated by the programmer (e.g.,
mallocin C,newin C++). - Global/Static Data Area: Global variables and static variables are stored together. Initialized global/static variables reside in one region, and uninitialized ones reside in an adjacent region. Memory is released when the program ends.
- Code Area: Stores the program's executable instructions.
static in C++
In C++, static retains all the properties it has in C, with additional functionality related to classes.
Static Member Variables
Static member variables (also called class variables) behave similarly to static local variables, but within the context of class instantiation:
- Static member variables are stored in the global/static area, so they do not occupy memory within each class instance. Consequently, they cannot be defined inside the class declaration; they must be defined and initialized outside the class.
- There is only one copy of a static member variable, shared by all instances (objects) of the class. Thus, they can be accessed using either the object-dot syntax (
obj.variable) or the class-scope resolution syntax (ClassName::variable). - They are not destroyed when an object is destroyed; they persist until the program ends.
- They are initialized only once, when the first object of the class is instantiated. Subsequent instantiations do not reinitialize them.
- They are persistent across object lifetimes, meaning the value set by one object is retained for the next object.
This behavior mirrors the behavior of static local variables in C, with the function's activation replaced by object instantiation.
Example:
#include <iostream>
using namespace std;
class Rectangle {
private:
int m_w, m_h;
static int s_sum;
public:
Rectangle(int w, int h) {
this->m_w = w;
this->m_h = h;
s_sum += (this->m_w * this->m_h);
}
void GetSum() {
cout << "sum = " << s_sum << endl;
}
};
int Rectangle::s_sum = 0; // Initialize static member
void test01() {
Rectangle rect1(3, 4);
rect1.GetSum();
cout << "sizeof(rect1)=" << sizeof(rect1) << endl;
}
int main() {
cout << "sizeof(Rectangle)=" << sizeof(Rectangle) << endl;
test01();
Rectangle rect2(2, 3);
rect2.GetSum();
cout << "sizeof(rect2)=" << sizeof(rect2) << endl;
system("pause");
return 0;
}
Output explanation:
sizeof(Rectangle)equals 8 (twointmembers), confirmings_sumdoes not occupy space in the class memory.- The summed area (18 = 12 + 6) demonstrates:
- The static member
s_sumis not destroyed whenrect1goes out of scope (at the end oftest01). s_sumis initialized only whenrect1is created, not again forrect2.- The value of
s_sumpersists fromrect1torect2.
- The static member
Static Member Functions
- Static member functions (also called class methods) are shared by all objects of the class.
- They can be defined inside or outside the class.
- They can be called using the class name and scope resolution operator (
ClassName::function()). - Crucially, static member functions do not have a
thispointer. Since they belong to the class as a whole, rather than any specific instance, they do not know which object called them. - Consequently, static member functions can only access static member variables and other static member functions. They cannot access non-static member variables or non-static member functions because they lack the
thispointer needed to identify a specific object.
Summary of interaction rules:
- Static members can freely access other static members (variables and functions).
- Non-static member functions can acces both static and non-static members.
- Static member functions cannot access non-static members (variables or functions).
Important note: Non-static member functions, static member functions, and static member variables all exist in only one copy per class and do not occupy memory in each object. However, non-static member functions know which object they are operating on via the implicit this pointer, which is provided by the caller. The this pointer points to the object that invoked the function.
const
While static deals with storage, lifetime, and scope, the const keyword primarily deals with access permissions, specifically making variables read-only.
const (Without Classes)
- A
constvariable must be initialized explicitly at the point of declaration. Once initialized, its value cannot be changed. - A non-
constvariable can be implicitly converted to aconsttype when needed (e.g., when passing to a function that expects aconstreference).
const (With Classes)
const Member Variables
constmember variables must be initialized using the member initializer list in the constructor. (This is also true for references and class types that lack a default constructor.)- Each object instance has its own copy of
constmember variables. They are initialized when the constructor is called via the initializer list.
const Member Functions (Const Functions)
To understand const member functions, it is essential to understand the this pointer. this is a pointer constant (ClassName * const this), meaning it always points to the object that invoked the member function and its own address cannot be changed. It is an implicit first parameter of every non-static member function.
In a const member function, the this pointer becomes of type const ClassName * const this. This implies that neither the pointer itself nor the object it points to can be modified. In other words, inside a const member function, you cannot modify any of the object's member variables (except those declared mutable or static).
Mutable member variables: Variables declared with the mutable keyword can be modified even inside a const member function.
Static member variables: const member functions can modify static member variables because static members are not associated with any specific instance.
Const Objects
- A const object can only call
constmember functions. It cannot call non-constmember functions. - A const object cannot modify its own member variables, except for
mutablemembers. - A const object can modify static member variables.
Non-const Objects
- A non-const object can call both
constand non-constmember functions. - It cannot modify its own
constmember variables.
Example:
#include <iostream>
using namespace std;
class Person {
public:
Person(int h) : h_(h) {}
int m_ = 10;
const int h_;
mutable int n_ = 20;
static int y_;
void fun() {}
void func() const {}
};
int Person::y_ = 40;
int main() {
const Person p1(3);
// p1.m_ = 20; // Error: cannot modify member of const object
// p1.h_ = 30; // Error: const member cannot be modified
p1.n_ = 40; // OK: mutable member
p1.y_ = 50; // OK: static member
// p1.fun(); // Error: non-const function cannot be called on const object
p1.func(); // OK: const function
Person p2(4);
p2.m_ = 20; // OK
// p2.h_ = 30; // Error: const member cannot be modified
p2.n_ = 40; // OK
p2.y_ = 50; // OK
p2.fun(); // OK
p2.func(); // OK
system("pause");
return 0;
}
Other Uses of const
Similar to static, a const variable declared at file scope has internal linkage by default in C++. This means it is visible only within the file where it is declared. Other files cannot reference or use it via extern. Therefore, declaring const variables in a header file is safe—even if the header is included by multiple source files, each translation unit gets its own copy, avoiding symbol redefinition errors.