Related Topics
C Programing
In C programming language, the static
keyword is used to declare variables, functions, and data structures with a “static storage duration.”
When a variable is declared as static inside a function, its value persists across multiple function calls. This is because the variable is not created on the stack and is instead allocated in the program’s data segment.
Similarly, when a function is declared as static, it becomes a private function that can only be called from within the same source file. This can be useful for encapsulating implementation details within a module and preventing external access.
In addition, static data structures can be used to maintain state across different function calls or even across different modules. For example, a static array can be used to keep track of the number of times a function has been called.
Overall, the static
keyword provides a way to control the scope and lifetime of variables and functions in a C program.
here are some examples of how to use the static
keyword in C programming:
Static variable inside a function:
#include <stdio.h>
void foo() {
static int count = 0;
count++;
printf("Count = %d\n", count);
}
int main() {
foo(); // prints "Count = 1"
foo(); // prints "Count = 2"
foo(); // prints "Count = 3"
return 0;
}
In this example, the count
variable is declared as static
inside the foo
function. This means that it retains its value across multiple function calls, allowing us to keep track of how many times the function has been called.
2. Static function
#include <stdio.h>
static int add(int x, int y) {
return x + y;
}
int main() {
printf("Result = %d\n", add(2, 3)); // prints "Result = 5"
return 0;
}
In this example, the add
function is declared as static
. This means that it has internal linkage and can only be called from within the same source file. This can be useful for encapsulating implementation details and preventing external access.
Static variable at file scope:
#include <stdio.h>
static int count = 0;
void foo() {
count++;
}
void bar() {
printf("Count = %d\n", count);
}
int main() {
foo();
foo();
bar(); // prints "Count = 2"
return 0;
}
In this example, the count
variable is declared as static
at file scope, outside of any function. This means that it has internal linkage and can only be accessed within the same source file. This can be useful for creating private variables that are only used within a specific module or source file.