static Storage Class
The static storage class is used to declare static variables which are popularly used while writing programs in C++ language. Static variables have the property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope.
We can say that they are initialized only once and exist until the termination of the program. Thus, no new memory is allocated because they are not re-declared. Global static variables can be accessed anywhere in the program.
Properties of static Storage Class
- Scope: Local
- Default Value: Zero
- Memory Location: RAM
- Lifetime: Till the end of the program
Note: Global Static variables can be accessed in any function.
Example of static Storage Class
C++
// C++ program to illustrate the static storage class // objects #include <iostream> using namespace std; // Function containing static variables // memory is retained during execution int staticFun() { cout << "For static variables: " ; static int count = 0; count++; return count; } // Function containing non-static variables // memory is destroyed int nonStaticFun() { cout << "For Non-Static variables: " ; int count = 0; count++; return count; } int main() { // Calling the static parts cout << staticFun() << "\n" ; cout << staticFun() << "\n" ; // Calling the non-static parts cout << nonStaticFun() << "\n" ; cout << nonStaticFun() << "\n" ; return 0; } |
For static variables: 1 For static variables: 2 For Non-Static variables: 1 For Non-Static variables: 1
Storage Classes in C++ with Examples
C++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specify the storage class for a variable.
Syntax
To specify the storage class for a variable, the following syntax is to be followed:
storage_class var_data_type var_name;
C++ uses 6 storage classes, which are as follows:
- auto Storage Class
- register Storage Class
- extern Storage Class
- static Storage Class
- mutable Storage Class
- thread_local Storage Class
Below is a detailed explanation of each storage class:
Contact Us