Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Storage of Static Variables:
2.1.
C++
3.
What are Static Variables in C++?
3.1.
C++
4.
Static Members of Class
4.1.
1. Static Data Members
4.2.
C++
4.3.
2. Static Member Functions:
4.4.
C++
5.
Frequently Asked Questions
5.1.
Can static variables be accessed outside the function or file where they are declared?
5.2.
Are static variables initialized every time a function is called?
5.3.
Can static member functions access non-static members of a class?
6.
Conclusion
Last Updated: Aug 23, 2024
Easy

C++ Static Variable

Author Rahul Singh
0 upvote

Introduction

Static variables in C++ are special types of variables that keep their values between function calls. Unlike regular variables that are created & destroyed within the scope of a function, static variables retain their values even after the function has finished executing. This means that the value of a static variable persists throughout the lifetime of the program, which makes it useful for storing data that needs to be accessed across multiple function calls. 

C++ Static Variable

In this article, we'll discuss the concept of static variables in C++, understand their storage & usage, and see how they can be applied in practical scenarios.

Storage of Static Variables:

When a static variable is declared in C++, it is stored in a special memory area called the static storage area. This memory area is separate from the stack & heap, which are used for storing regular variables. The static storage area is allocated when the program starts & remains available throughout the program's execution.

For example : 

  • C++

C++

#include <iostream>

void incrementCount() {

   static int count = 0;

   count++;

   std::cout << "Count: " << count << std::endl;

}

int main() {

   incrementCount();

   incrementCount();

   incrementCount();

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

 

In this example, the `count` variable is declared as static inside the `incrementCount` function. When the function is called for the first time, `count` is initialized to 0. Each subsequent call to `incrementCount` increments the value of `count`, and the updated value is printed.

Output

Count: 1
Count: 2
Count: 3


As you can see, the value of `count` persists between function calls. Even though `incrementCount` is called multiple times, `count` retains its value and continues to increment.

Note: The static storage area ensures that static variables maintain their values throughout the program's execution, which makes them useful for storing data that needs to be accessed & modified across different function calls.

What are Static Variables in C++?

Static variables in C++ have several key characteristics that distinguish them from regular variables:

1. Initialization: Static variables are initialized only once, when the program starts. They are initialized with a default value of 0 for numeric types, an empty string for strings, or a null pointer for pointers. You can also explicitly initialize a static variable with a specific value.

2. Scope: Static variables have a global scope within the function or file where they are declared. They can be accessed from any part of the function or file, but they are not visible outside of it.

3. Lifetime: Static variables have a lifetime that extends throughout the entire program execution. They are created when the program starts and destroyed when the program ends. This means that their values persist between function calls.

4. Memory Allocation: Static variables are allocated memory in the static storage area, which is separate from the stack and heap. The memory for static variables is allocated only once, during program startup, and remains allocated until the program terminates.

For example : 

  • C++

C++

#include <iostream>

void countCalls() {

   static int callCount = 0;

   callCount++;

   std::cout << "Function called " << callCount << " times." << std::endl;

}

int main() {

   countCalls();

   countCalls();

   countCalls();

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code


Output:

Function called 1 times.
Function called 2 times.
Function called 3 times.


In this example, the `callCount` variable is declared as static inside the `countCalls` function. It is initialized to 0 only once, when the program starts. Each time `countCalls` is called, `callCount` is incremented, and the updated value is printed.

Static variables are commonly used for maintaining state between function calls, implementing counters, and storing global data that needs to be accessed from multiple functions within a file.

Note: It's important to use static variables with caution, as they can introduce a global state and make code harder to understand and maintain if overused. They should be used when there is a clear need for data to persist across function calls or when global data needs to be shared within a limited scope.

Static Members of Class

In C++, static members can also be used within classes. Static members of a class are shared among all objects of that class, rather than being unique to each object. There are two types of static members in classes:

1. Static Data Members

   - Static data members are variables that belong to the class itself, rather than to individual objects of the class.

   - They are declared using the `static` keyword within the class definition.
 

   - Static data members are initialized outside the class definition, in the global scope.
 

   - They can be accessed using the class name followed by the scope resolution operator (`::`).
 

   - Static data members are useful for maintaining shared data across all objects of a class.
 

For Example:

  • C++

C++

#include <iostream>

class Student {

public:

   static int totalStudents;

   Student() {

       totalStudents++;

   }

};

int Student::totalStudents = 0;

int main() {

   Student student1;

   Student student2;

   Student student3;

   std::cout << "Total students: " << Student::totalStudents << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

 

Output

Total students: 3


In this example, `totalStudents` is a static data member of the `Student` class. It is incremented each time a new `Student` object is created. The total count of students can be accessed using `Student::totalStudents` without the need for an object.

2. Static Member Functions:

   - Static member functions are functions that belong to the class itself, rather than to individual objects of the class.

   - They are declared using the `static` keyword within the class definition.
 

   - Static member functions can only access static data members and other static member functions of the class directly.
 

   - They do not have a `this` pointer, as they are not associated with any specific object.
 

   - Static member functions are useful for performing operations that are related to the class as a whole, rather than to individual objects.


For Example:

  • C++

C++

#include <iostream>

class MathUtility {

public:

   static int add(int a, int b) {

       return a + b;

   }

};

int main() {

   int result = MathUtility::add(5, 3);

   std::cout << "Result: " << result << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

 

Output

Result: 8


In this example, `add` is a static member function of the `MathUtility` class. It can be called directly using the class name (`MathUtility::add`) without the need for an object. The `add` function takes two integers as arguments and returns their sum.

Note: Static members of classes provide a way to share data and functionality among all objects of a class, allowing for more efficient memory usage and convenient access to class-level information.

Frequently Asked Questions

Can static variables be accessed outside the function or file where they are declared?

No, static variables have a limited scope within the function or file where they are declared. They cannot be accessed from outside that scope.

Are static variables initialized every time a function is called?

No, static variables are initialized only once, when the program starts. They retain their values between function calls.

Can static member functions access non-static members of a class?

No, static member functions can only access static data members and other static member functions of the class directly. They cannot access non-static members without an object.

Conclusion

In this article, we learned about static variables in C++. We explained their storage, characteristics, and usage. Static variables are stored in a special memory area called the static storage area and retain their values throughout the program's execution. They are initialized only once and have a global scope within the function or file where they are declared. We also discussed static members of classes, including static data members and static member functions. Static members are shared among all objects of a class and provide a way to maintain class-level data and functionality. 


You can also check out our other blogs on Code360.

Live masterclass