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

Static Variables in C

Last Updated : 04 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In C programming, a static variable is declared using static keyword and have the property of retaining their value between multiple function calls. It is initialized only once and is not destroyed when the function returns a value. It extends the lifetime of the variable till the end of the program.

Example:

C
#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 

Explanation: The above program prints 1 2 because static variables count is only initialized once. In the first call to fun(), count in increased to 1 which is printed. In the second call, normal local variable would have value 1 as it would have been created and initialized again, but count variable is 2 because it was not destroyed with the function. That is why it was able to retain its value between multiple function calls.

Syntax

The static variable can be simply declared by prefixing the static keyword before the normal variable declaration.

static dataType variableName;

Examples of static Variables

The following examples demonstrate the use of static variables in C programs:

Return Address of Local Variable from a Function

As static variables live till the end of the program, we can use them to return data by reference from a function in C:

C
#include <stdio.h>
int* fun() {
    
    // Create and Return static variable
    static int local_var = 123;
    return &local_var;
    
}
int main() {
    printf("%d", *fun());
    return 0;
}

Output
123

Explanation: In this program, fun() returns a pointer to the static local variable local_var, which retains its value even after the function exits. Unlike normal local variables, which are destroyed when function exists.

Control Recursion Depth

As these variables are only initialized once and retain their value, they can be used to control the recursion in case of infinite recursive calls.

C
#include <stdio.h>

// recursive function that runs from n to 0
void fun(int n){
    if (n == 0) return;
    printf("%d ", n);
    fun(n - 1);
}
int main(){
    fun(-1);
    return 0;
}


Output

(infinite recursion)

The above program is an example where a specific value of n (here all negative values) leads to infinite recursion. A static variable can be used to control the recursion depth in this case and avoid the stack overflow.

C
#include <stdio.h>

// Recursive function that runs from n to 0
// It will terminate for recursive depth
// greater than 10
void fun(int n){
    
    // Static variable
    static int depth = 0;
    if (n == 0 || depth > 10) return;
    printf("%d ", n);
    
    // Increasing with number of recursive calls
    depth++;
    fun(n - 1);
}
int main(){
    fun(-1);
    return 0;
}

Output
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 

Explanation: In this program, the static variable depth retains its value across recursive calls, allowing the function to track the recursion depth. It ensures the recursion terminates when depth > 10, preventing excessive recursive calls and potential stack overflow.

Global Static Variables

Static variables are generally declared inside functions, but they can also be declared outside functions (at the global scope). Global static variables have their scope limited to the file they are defined in (internal linkage). It means that they cannot be accessed outside the current translation unit (C source file).

Other than that, there is no effect of static on global variables in C.

Example:

C
#include <stdio.h>

// Static global variable
static int globalVar = 5;

void display() {
    printf("%d\n", globalVar);
}
int main() {
    display();  
    globalVar = 10;
    display();  
    return 0;
}

Output
5
10

Interesting Facts

Following are some interesting facts about static variables:

  • Static variables (like global variables) are initialized as 0 if not initialized explicitly. See this for more details. 
  • In C, static variables can only be initialized using constant literals. See this for more details.

Local vs Static Local Variables

The static local variables and local variables behave differently from each other. Following table lists the primary differences between them:

Local VariableStatic Variable
Local to the function or blockLocal to the function or block
Exists only during function executionExists throughout the program execution
Reinitialized each time function is calledInitialized only once
Stored in the stackStored in the data segment

Master C with our C Programming online course! From basics to advanced topics like data structures, enhance your skills with hands-on coding challenges. Take the Three 90 Challenge—complete 90% in 90 days, and earn a 90% refund. Start your learning journey today!


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 acces
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
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 global and static variables in C
Predict the output of following C programs. C // PROGRAM 1 #include <stdio.h> #include <stdlib.h> int main(void) { static int *p = (int*)malloc(sizeof(p)); *p = 10; printf("%d", *p); } C // PROGRAM 2 #include <stdio.h> #include <stdlib.h> int *p = (int*)malloc(sizeof(p)); int main(void) { *p = 10; printf("%d
1 min read
Initialization of Static Variables in C
In C, a static variable are those variables whose lifetime is till the end of the program. It means that once it is initialized, it will live in the program till it ends. It can retain its value between function calls, unlike regular local variables that are reinitialized each time the function is called.Syntax of InitializationInitializing a stati
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
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
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 o
2 min read