The Wayback Machine - https://web.archive.org/web/20240907044702/https://www.geeksforgeeks.org/static-variables-in-c/
Open In App

Static Variables in C

Last Updated : 16 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Static variables have the property of preserving their value even after they are out of their scope! Hence, a static variable preserves its previous value in its previous scope and is not initialized again in the new scope. 

Syntax:

static data_type var_name = var_value;

Following are some interesting facts about static variables in C:

1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over. 
For example, we can use static int to count the number of times a function is called, but an auto variable can’t be used for this purpose.

Example

C




// C Program to illustrate the static variable lifetime
#include <stdio.h>
 
// function with static variable
int fun()
{
    static int count = 0;
    count++;
    return count;
}
 
int main()
{
    printf("%d ", fun());
    printf("%d ", fun());
    return 0;
}


Output

1 2 

The above program prints 1 2 because static variables are only initialized once and live till the end of the program. That is why they can retain their value between multiple function calls.

Let’s try the same code for the local auto variable.

Example

C




// C Program to illustrate local auto variable in comparison
// of static variable.
#include <stdio.h>
 
// Function
int fun()
{
    int count = 0;
    count++;
    return count;
}
 
// Driver Code
int main()
{
    printf("%d ", fun());
    printf("%d ", fun());
    return 0;
}


Output

1 1 

2) Static variables are allocated memory in the data segment, not the stack segment. See the memory layout of C programs for details.

3) Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, the value of x is printed as 0, while the value of y is something garbage. See this for more details. 

Example

C




// C program to illustrate the default value of static
// variables
#include <stdio.h>
 
int main()
{
    static int x;
    int y;
    printf("%d \n%d", x, y);
}


Output

0 
[some_garbage_value]

4) In C, static variables can only be initialized using constant literals. For example, the following program fails in the compilation. See this for more details.

Example

C




#include<stdio.h>
int initializer(void)
{
    return 50;
}
  
int main()
{
    static int i = initializer();
    printf(" value of i = %d", i);
    getchar();
    return 0;
}


Output

In function 'main':
9:5: error: initializer element is not constant
static int i = initializer();
^

Note: Please note that this condition doesn’t hold in C++. So if you save the program as a C++ program, it would compile and run fine.

5) Static global variables and functions are also possible in C/C++. The purpose of these is to limit the scope of a variable or function to a file. Please refer to Static functions in C for more details.

6) Static variables should not be declared inside a structure. The reason is C compiler requires the entire structure elements to be placed together (i.e.) memory allocation for structure members should be contiguous. It is possible to declare structure inside the function (stack segment) or allocate memory dynamically(heap segment) or it can be even global (BSS or data segment). Whatever might be the case, all structure members should reside in the same memory segment because the value for the structure element is fetched by counting the offset of the element from the beginning address of the structure. Separating out one member alone to a data segment defeats the purpose of structure and it is possible to have an entire structure as static.

Related Articles:  



Previous Article
Next Article

Similar Reads

Difference between Static variables and Register variables in C
static variables Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope. Syntax: static data_type var_name = var_value; register variables Registers are faster than memory to access
2 min read
Internal static variable vs. External static variable with Examples in C
The static variable may be internal or external depending on the place of declaration. Both kinds of static variables are stored in initialized data segments. Internal Static Variables Internal Static variables are defined as those having static variables which are declared inside a function and extend up to the end of the particular function. Synt
2 min read
How are variables scoped in C - Static or Dynamic?
In C, variables are always statically (or lexically) scoped i.e., binding of a variable can be determined by program text and is independent of the run-time function call stack. For example, output for the below program is 0, i.e., the value returned by f() is not dependent on who is calling it. f() always returns the value of the global variable x
1 min read
What are the default values of static variables in C?
In C, if an object that has static storage duration is not initialized explicitly, then: — if it has pointer type, it is initialized to a NULL pointer; — if it has an arithmetic type, it is initialized to (positive or unsigned) zero; — if it is an aggregate, every member is initialized (recursively) according to these rules; — if it is a union, the
2 min read
Initialization of static variables in C
In C, static variables can only be initialized using constant literals. For example, following program fails in compilation. #include&lt;stdio.h&gt; int initializer(void) { return 50; } int main() { static int i = initializer(); printf(&quot; value of i = %d&quot;, i); getchar(); return 0; } If we change the program to following, then it works with
1 min read
Initialization of global and static variables in C
Predict the output of following C programs. // PROGRAM 1 #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(void) { static int *p = (int*)malloc(sizeof(p)); *p = 10; printf(&quot;%d&quot;, *p); } // PROGRAM 2 #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int *p = (int*)malloc(sizeof(p)); int main(void) { *p = 10; printf(&quot;%d&quot;
1 min read
C++ | Static Keyword | Question 1
Predict the output of following C++ program. #include &lt;iostream&gt; using namespace std; class Test { static int x; public: Test() { x++; } static int getX() {return x;} }; int Test::x = 0; int main() { cout &lt;&lt; Test::getX() &lt;&lt; &quot; &quot;; Test t[5]; cout &lt;&lt; Test::getX(); } (A) 0 0 (B) 5 5 (C) 0 5 (D) Compiler Error Answer: (
1 min read
C++ | Static Keyword | Question 2
#include &lt;iostream&gt; using namespace std; class Player { private: int id; static int next_id; public: int getID() { return id; } Player() { id = next_id++; } }; int Player::next_id = 1; int main() { Player p1; Player p2; Player p3; cout &lt;&lt; p1.getID() &lt;&lt; &quot; &quot;; cout &lt;&lt; p2.getID() &lt;&lt; &quot; &quot;; cout &lt;&lt; p
1 min read
C++ | Static Keyword | Question 4
Predict the output of following C++ program. #include &lt;iostream&gt; using namespace std; class A { private: int x; public: A(int _x) { x = _x; } int get() { return x; } }; class B { static A a; public: static int get() { return a.get(); } }; int main(void) { B b; cout &lt;&lt; b.get(); return 0; } (A) 0 (B) Linker Error: Undefined reference B::a
1 min read
C++ | Static Keyword | Question 5
#include&lt;iostream&gt; using namespace std; class Test { private: static int count; public: Test&amp; fun(); }; int Test::count = 0; Test&amp; Test::fun() { Test::count++; cout &lt;&lt; Test::count &lt;&lt; &quot; &quot;; return *this; } int main() { Test t; t.fun().fun().fun().fun(); return 0; } (A) Compiler Error (B) 4 4 4 4 (C) 1 1 1 1 (D) 1 2
1 min read
C++ | Static Keyword | Question 6
Output of following C++ program? #include &lt;iostream&gt; class Test { public: void fun(); }; static void Test::fun() { std::cout&lt;&lt;&quot;fun() is static\n&quot;; } int main() { Test::fun(); return 0; } Contributed by Pravasi Meet (A) fun() is static (B) Empty Screen (C) Compiler Error Answer: (C) Explanation: The above program fails in compi
1 min read
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
Difference between Static and Shared libraries
In programming, a library is a collection of pre-compiled pieces of code that can be reused in a program. Libraries simplify life for programmers, in that they provide reusable functions, routines, classes, data structures and so on which they can be reused in the programs. Static Libraries: A Static library or statically-linked library is a set of
2 min read
“static const” vs “#define” vs “enum”
In this article, we will be analyzing "static const", "#define" and "enum". These three are often confusing and choosing which one to use can sometimes be a difficult task. static const static const : "static const" is basically a combination of static(a storage specifier) and const(a type qualifier). Static : determines the lifetime and visibility
4 min read
Static functions in C
In C, functions are global by default. The “static” keyword before a function name makes it static. For example, the below function fun() is static. C/C++ Code static int fun(void) { printf(&quot;I am a static function &quot;); } Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, w
1 min read
Can Static Functions Be Virtual in C++?
In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren't tied to the instance of a class but they are tied to the class. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function v
1 min read
How to Create a Static Library in C?
In C, we can create our own libraries that contains the code for the functions or macros that we may need very often. These libraries can be then used in our programs. In this article, we will learn how to create a custom static library and use it with GCC compiler. What is a Static Libraries in C?A static library is a collection of object files th
2 min read
Difference between Static and Dynamic Memory Allocation in C
Memory Allocation: Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space. The memory allocation is done either before or at the time of program execution. There are two types of memory allocations: Compile-time or Static Memory AllocationRun-time or Dynamic Memory AllocationStatic
3 min read
How will you show memory representation of C variables?
Write a C program to show memory representation of C variables like int, float, pointer, etc. Algorithm: Get the address and size of the variable. Typecast the address to char pointer. Now loop for size of the variable and print the value at the typecasted pointer.Program: C/C++ Code #include &amp;lt;stdio.h&amp;gt; typedef unsigned char *byte_poin
1 min read
Difference Between Constants and Variables in C
The constants and variables in C are both used to store data. So it is essential to know the difference between the variables and constants in C so that we can decide which one to use based on the situation. In this article, we will discuss the basic difference between a constant and a variable in C language. Variables in C A variable in simple ter
3 min read
Problem Solving on Storage Classes and Scoping of Variables
Storage class of variables includes the scope, visibility and life-time which help to trace the existence of a particular variable during the runtime of a program. There exist four types of storage classes in C: auto, register, static and extern. Auto and Register Storage Classes - The scope of variable declared using auto or register storage class
8 min read
Linking Files having same variables with different data types in C
Suppose there are two codes foo1.c and foo2.c as below and here the task is to link foo1.c and foo2.c which have same variable name x but different data type i.e int in foo1.c and double in foo2.c. Note that none of the variables is declared as extern. What do you expect to be the output of the following command with given two programs? $ gcc -o my
2 min read
Implicit initialization of variables with 0 or 1 in C
In C programming language, the variables should be declared before a value is assigned to it. For Example: // declaration of variable a and // initializing it with 0. int a = 0; // declaring array arr and initializing // all the values of arr as 0. int arr[5] = {0}; However, variables can be assigned with 0 or 1 without even declaring them. Let us
2 min read
Can Global Variables be dangerous ?
In a small code, we can track values of global variables. But if the code size grows, they make code less understandable (hence less maintainable). It becomes difficult to track which function modified the value and how. C/C++ Code // A C++ program to demonstrate that a // global variables make long code less // maintainable. int c = 1; int fun1()
2 min read
Global Variables in C
Prerequisite: Variables in C In a programming language, each variable has a particular scope attached to them. The scope is either local or global. This article will go through global variables, their advantages, and their properties. The Declaration of a global variable is very similar to that of a local variable. The only difference is that the g
3 min read
Why do we need reference variables if we have pointers
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do w
4 min read
Difference between Identifiers and Variables in C
Perquisites: Identifiers, Variables Identifiers Identifiers are used for the naming of variables, functions, and arrays. It is a string of alphanumeric characters that begins with an alphabet, or an underscore( _ ) that are used for variables, functions, arrays, structures, unions, and so on. It is also known as the user-defined word. Identifier na
2 min read
Operations on struct variables in C
In C, the only operation that can be applied to struct variables is assignment. Any other operation (e.g. equality check) is not allowed on struct variables. For example, program 1 works without any error and program 2 fails in compilation. Program 1 #include &lt;stdio.h&gt; struct Point { int x; int y; }; int main() { struct Point p1 = {10, 20}; s
1 min read
Initialization of variables sized arrays in C
The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized. For example, the following program compiles and runs fine on a C99 compatible compiler. #include&lt;stdio.h&gt; int main() { int M = 2; int arr[M][M]; int i, j; for (i = 0; i &lt; M; i++) { for (j = 0; j &lt; M; j++)
1 min read
C Program to print environment variables
The C standard says following about main function in C. The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters: int main(void) { /* ... */ } or with two parameters (referred to here as argc and argv, though any names may b
1 min read