It has the following syntax:
static data_type variable_name = value;
- data_type: The data type (int, char, float, etc.).
- variable_name: The name of the variable.
- value: The initial value (defaults to 0 if not specified).
Basic Example of the Static Keyword in C
Let's consider an example to demonstrate the application of the static keyword in the C programming language.
Example
#include <stdio.h>
//Using a function with a static local variable
void displayCounter() {
static int count = 0; //using static variable
count++;
printf("Function called %d\n", count);
}
int main() { //main function
// Call the function multiple times
displayCounter();
displayCounter();
displayCounter();
return 0;
}
Output:
Function called 1
Function called 2
Function called 3
Explanation:
In this instance, we are utilizing the count variable declared as static. This variable is initialized just once and preserves its value across multiple calls to the function. Subsequently, with each invocation of displayCounter, the count increases and displays the revised value.
Usage of the Static keyword in C
There are multiple applications of the static keyword in the C programming language. A few of these are outlined below:
1. Static Local Variables
In the realm of C programming, local variables with static storage duration are defined within functions by utilizing the static keyword. These variables maintain their values across multiple function invocations, yet their scope is limited to the function itself.
Static Local Variables Example in C
Let's consider an example to demonstrate the usage of a static local variable in the C programming language.
Example
#include <stdio.h>
void addStudent(const char* name) {
static int roll_num = 1001; //using static variable
printf("Student Name: %s\n", name);
printf("Roll Number: %d\n\n", roll_num);
roll_num++; // Increment for next student
}
int main() { //main function
addStudent("Jhonson");
addStudent("Daniel");
addStudent("Peter");
return 0;
}
Output:
Student Name: Jhonson
Roll Number: 1001
Student Name: Daniel
Roll Number: 1002
Student Name: Peter
Roll Number: 1003
Explanation:
In this instance, we are utilizing the static variable roll_num, which preserves its value throughout various invocations of the addStudent function. Subsequently, each student is allocated a distinct roll number commencing from 1001, with an increment occurring after each function invocation.
2) Static Global Variables
Declaring a global variable with the static keyword limits its scope to the current file, making it inaccessible from other files within the project. This practice effectively encapsulates the variable, reducing the chances of naming clashes.
Static Global Variable Example in C
Let's consider an example to demonstrate the concept of a static global variable in the C programming language.
Example
#include <stdio.h>
static int global_count_variable = 10;
void print()
{
printf("The Global Count is: %d\n", global_count_variable);
}
int main() //main function
{
print();
return 0;
}
Output:
The Global Count is: 10
Explanation:
In this instance, we've utilized the globalcountvariable, defined as static at the global scope, limiting its visibility to just this particular file. Subsequently, the print function retrieves and displays its value.
3) Static Functions
In C programming, a function defined with the static keyword is solely accessible within the same file where it is declared. This restriction prevents external files from accessing it, thereby enhancing the encapsulation of auxiliary functions in extensive C projects.
Static Functions Example in C
Let's consider an example to demonstrate the static function in the C programming language.
Example
#include <stdio.h>
static void greet()
{
printf("Welcome to the static block!\n");
}
int main() //main function
{
greet();
return 0;
}
Output:
Welcome to the static block!
Explanation:
In this instance, we define a greet function as static, indicating it possesses internal linkage and is restricted to access within the same source file. Subsequently, the main function invokes the greet function, displaying the welcome message.
ImportanLogic Practices to remember about static variables in C
There are several key principles to keep in mind regarding static variables in the C programming language. Some of these are as follows:
Lifetime and function calls
A static variable maintains its value in memory throughout the program's execution, persisting even after the function where it is declared finishes its execution. In contrast, a regular (auto) variable gets destroyed once the function's execution is completed.
Memory Allocation
Static variables are allocated memory in the data segment instead of the stack, allowing them to persist throughout the program's execution rather than getting deallocated when a function ends.
Default initialization
If a static variable isn't explicitly initialized, it defaults to 0, similar to a global variable. In contrast, uninitialized local (auto) variables hold random values.
Default Initialization Example in C:
Let's consider an example to demonstrate the default initialization in C programming.
Example
#include <stdio.h>
int main() //main function
{
static int q;
int r;
printf("%d\n%d", q, r);
}
Output:
0
32545
Initialization Rules:
Static variables are restricted to being initialized solely with constant literals like 0, 5, or 'A'. It is not permissible to assign them initial values derived from functions or runtime expressions. However, this constraint does not hold true in the context of C++, as static variables are allowed to be initialized using non-constant values.
Static functions and global variables:
In the C programming language, we have the ability to define static global variables and static functions. This restriction confines their visibility to the specific file in which they are defined. This restriction ensures that they are inaccessible from other files within the project, promoting modularity and averting potential naming clashes.
Static Variables Inside Structures:
In the C programming language, it is not possible to define static variables within structures. This restriction exists because structures are required to store all their members in a contiguous block of memory. Introducing a static variable (which resides in the data segment) within a structure would violate this rule, leading to an inconsistent layout of the structure.
Differences between Static and Global Variables
In C programming, global variables are those variables declared outside a function. These variables are available from the start to the end of the program and can be accessed from anywhere within the program. In contrast, static variables are confined to the source file where they are defined, meaning they are not accessible from other source files.
Both static and global variables undergo static initialization. In this context, static initialization implies that if no value is explicitly assigned to the variable, it will automatically default to 0.
Properties of a Static Variable in C
The following are the properties of a static variable in C.
- The memory of a static variable is allocated within a static variable.
- Its memory is available throughout the program, but the scope will remain the same as the automatic local variables.
- Its value will persist across the various function calls.
- If we do not assign any value to the variable, the default value will be 0.
- A global static variable cannot be accessed outside the program, while a global variable can be accessed by other source files.