Introduction
We can use a Static keyword in the C Programming language with both functions and variables, i.e., we may declare a static function and a static variable. A standard variable is limited to its scope, while the scope of a static variable is throughout the program. The static keyword in C has the property of preserving its value even after it is out of scope.
In this article, we will focus on the static keyword in C. We will discuss scenarios to use static keywords, with examples of static variables and static functions.
What is static keyword in C?
The static keyword in C is a storage class specifier. It has different meanings based on the context. Within a function, it makes the variable retain its value among multiple function calls. Outside of a function, it restrains the visibility of the variable or function to the current file.
We can use static keywords in C for the following scenarios−
- Static function: If the function is declared with the static keyword, it is known as a static function. Its lifetime is through the complete program.
- Static global variable: When we declare any global variable with a static keyword, it is known as a static global variable. Generally, we declare a static global variable at the top of the program, and its visibility is throughout the program.
- Static local variable: When a lthe ocal variable is declared with a static keyword, it is known as a static local variable. Local variables have the scope that, they are visible only within the block or function like local variables have the scope that, they are visible only within the block or function like local variables.
- Static method: If we declare the member function of a class with a static keyword in C, it is known as a static method. We can access it through all the instances of the class.
- Static member variables: If we declare the member variables of a class with a static keyword in C, it is known as a static method. We can access it through all the instances of the class.
Must Read Static Blocks In Java
Syntax
The syntax for a static keyword in C is given below:
// Static Keyword in C for variables
static <variable_type> <variable_name>
<variable_type> static <variable_name>
// Static Keyword in C for functions
static <function_type> <function_name>()
<function_type> static <function_name>()
You can also read about the jump statement