C++ Static Variable14 Jun 2025 | 7 min read In C++, static variables are a type of variable whose lifetime extends the whole program's execution but whose scope can be restricted based on where they are defined. We recently covered how the static keyword changes the behaviour of a variable, which ensures that its value remains long after the block or function in which it is defined has completed execution. Static variables are very useful when we need to save a common property or track shared data across multiple objects. They contribute to less redundancy and greater consistency across all instances. C Static Variable ExampleLet us take an example to illustrate the Static variable in C. ExampleCompile and RunOutput: Account Holder Name: Joseph, Balance: $50000 Account Holder Name: John, Balance: $40000 Account Holder Name: Mary, Balance: $20000 Total Bank Accounts Created: 3 Explanation: In this example, we define a tpointTech class that represents a bank account and a static variable total_accounts, which keeps track of the total number of accounts created. When a tpointTech object is created, the constructor sets the account information and increases total_accounts, which is shared by all instances. After creating three accounts and presenting their information, the program uses the static variable to calculate the overall number of accounts created. Types of Static Variables in C++There are several static variables that can also be categorized into three essential categories:
Static Variables Inside FunctionsIn C++, when a variable is declared as static inside the function, its value is retained across successive calls to the function. Generally, local variables are created when a function begins and removed when it ends. However, a static local variable is initialized only once the first time the function is called and lives until the program ends. Each successive call to the function sees the static variable's most recent modified value. C++ Static Variable Inside Functions Example Let us take an example to illustrate the Static variables inside functions in C++. ExampleCompile and RunOutput: Count is: 1 Count is: 2 Count is: 3 Explanation: In this program, we have taken a display() function that contains a static variable c, which is initialized only once and preserves its value between functions. Each time the display() function is called, c is incremented by one and printed. As a result, running the display() function three times produces the outputs 1, 2, and 3 in order. Static Member Variables in ClassesWhen a variable is specified as static within a class, it belongs to the class rather than a specific object. It signifies that all instances of the class use the same static variable. Static members are initialized outside of the class and exist independently of any of its objects. C++ Static Member Variables in Classes Example Let us take an example to illustrate the Static member variable in Classes in C++. ExampleCompile and RunOutput: Total objects created are: 3 Explanation: In this example, we have taken the tpointTech class that includes a static member object_count function that keeps track of how many objects of the class have been created. After that, the object_count function is updated every time the constructor is called. Three objects (a, b, and c) are created in the main() function. Global Static VariablesIn C++, when a global variable is declared in the program with the static keyword, its scope is limited to the source file. It means that the variable cannot be accessed from other files. It is also useful to encapsulate and helps to hide implementation details and prevent naming conflicts in huge programs with several source files. C++ Global Static Variables Example Let us take an instance to demonstrate the Global static variable in C++. ExampleCompile and RunOutput: Connecting to database... Connection count: 1 Connecting to database... Connection count: 2 Database connection closed. Remaining connections: 1 Explanation: In this example, we simulate a simple database connection tracker using a global static variable db_connection_count. After that, every call to ConnectToDatabase() function helps to increases the count, and CloseDatabaseConnection() function helps to decreases the cout, which ensures that only active connections are closed. Finally, the output displays the connection and disconnection process in sequence. Storage of Static Variables in C++ In C++, the static variable is used to allocate memory once during the program's lifetime, and it retains its value between function calls. Unlike local variable that are stored on the stack, static variables are mainly stored in a special memory area that is known as data segment. If a static variable is clearly initialized in the program, its value is stored in the initialized data segment. If it is not clearly initialized in the program, it is automatically set to 0 and placed in the BSS (Block Started by Symbol) segment, which holds uninitialized static or global variables. It means that the memory used by static variables is kept throughout the program, regardless of whether the function or scope in which they were defined has ended. Applications of Static Variables in C++Several applications of static variables in C++ are as follows:
C++ Static Variables MCQs1) What is the lifetime of a static variable defined within a function in C++?
Answer: c) Until the program ends. 2) Which of the following options correctly declares a static variable inside a class in C++?
Answer: a) int static count; 3) Which of the following options shows the scope of a global static variable in C++?
Answer: c) The file in which it is declared 4) When a static variable is initialized inside a function in C++?
Answer: b) Only once, on the first function call 5) What happens if a static variable is accessed without first being initialized in C++?
Answer: d) It is initialized to zero by default Next TopicC++ Template Specialization |
Linear Equation is a basic concept in mathematics and science. Linear equations are important in many disciplines, such as computer science, economics, physics, and engineering. It is necessary to express systems of linear equations in matrix form to solve them quickly. What is a System of Linear...
4 min read
In this article, we will write a program to add two complex numbers (a1 + ib1) and (a2 + ib2) using class. For example Input: 4 + i5 and 8 + i9 Here a1= 4 and a2 = 8. On adding a1 and a2, we get (8 + 4)...
4 min read
Introduction: The tellp() function returns the pointer's current "put" position in the stream when used with output streams. It has no parameters and returns a value of the member type pos_type, an integer data type that represents the put stream pointer's current position. Syntax: pos_typetellp(); Return - If successful, the current...
1 min read
Trees are essential in the field of computer science and data structures for effectively organizing and managing data. In real-world applications, trees are hierarchical structures that are used to depict a variety of connections and hierarchies. They are the cornerstone of computer science since they are...
11 min read
Are you struggling to make sense of strings with inconsistent formatting in your C++ code? Converting between different styles of string formatting can be a common challenge for programmers, particularly when dealing with Camel Case and Snake Case. Converting a Camel Case string to a Snake Case...
12 min read
If you're dealing with visuals, writing a game demands some solid programming skills as well as a strong grasp of a few APIs, such as OpenGL and DirectX. For C++ programmers, there are a few gaming engines available to make the process straightforward. Necessary Header files The...
4 min read
Class member methods are non-virtual by default in C++. This means that by specifying it, they can be made virtual. Methods in Java, on the other hand, are virtual by default and can be made non-virtual by using the 'final' keyword. Let's look at how the default virtual...
2 min read
In this article, you will learn about the mbrtoc32() function in C++ with its syntax, parameters, and examples. A multibyte character sequence in C/C++ can be converted to a wide character (more precisely, a 32-bit wide character represented by char32_t) using the mbrtoc32() function in the standard...
3 min read
An array is a group of related data pieces kept in close proximity to one another in memory. The sole way to retrieve each data piece directly is by using its index number, making it the most basic data structure. Arranging the array's items in ascending order...
4 min read
Algorithms that only use integer operations must be used to draw circles without the use of floating-point math. Bresenham's circle drawing algorithm is one of the regularly used algorithms for this purpose. Using solely integer arithmetic, this approach efficiently and effectively creates circles. A version of Bresenham's...
6 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India