Differentiate between an internal static and external static variable?
Understanding the Differences between Internal Static and External Static Variables in C Programming
The main difference between an internal static variable and an external static variable is their scope and linkage.
- Internal static variables are declared inside a function with the static keyword. They have block scope, which means they are only visible within the function in which they are declared. They also have no linkage, which means they are not visible to other functions in the same file.
- External static variables are declared outside of all functions with the static keyword. They have file scope, which means they are visible to all functions in the same file. They also have internal linkage, which means they are only visible to other functions in the same file.
Here is a table summarizing the differences between internal static variables and external static variables:
Feature | Internal static variable | External static variable |
---|---|---|
Scope | Block scope | File scope |
Linkage | No linkage | Internal linkage |
Lifetime | Exists until the end of the function | Exists until the end of the program |
Initialization | Can be initialized or not | Must be initialized |
Here is an example of an internal static variable:
C Programming
void foo() {
static int i = 10; // Internal static variable
i++;
printf("i = %d\n", i);
}
In this example, the variable i is declared as static inside the function foo(). This means that i is only visible within foo(). The variable i is also initialized to 10 when foo() is called for the first time.
Here is an example of an external static variable:
C Programming
static int j = 20; // External static variable
void foo() {
printf("j = %d\n", j);
}
void bar() {
printf("j = %d\n", j);
}
In this example, the variable j is declared as static outside of any function. This means that j is visible to all functions in the same file. The variable j must be initialized when the program is compiled.