In C/C++ and similar programming languages, global variables and static variables differ in the following aspects:
Storage Area:
- Global variables: Global variables are stored in the program's global data segment, which persists throughout the program's lifetime.
- Static variables: Static variables may be stored in the global data segment or within functions, depending on their declaration position. However, regardless of storage location, static variables have a lifetime spanning the entire program execution.
Initialization:
- Global variables: If not explicitly initialized, global variables are automatically initialized to 0.
- Static variables: Similarly, if not explicitly initialized, static variables are automatically initialized to 0.
Scope:
- Global variables: Global variables have global scope, meaning they can be accessed throughout the program unless hidden within a local scope.
- Static variables:
- If declared as a static local variable within a function, it is visible only within that function, but its value persists between function calls.
- If declared at file scope as a static global variable, its scope is limited to the file in which it is declared, and it is not visible to other files.
Linkage:
- Global variables: Global variables have external linkage (unless declared as
static), meaning they can be accessed by other files in the program (with appropriate declarations likeextern). - Static variables:
- Static global variables have internal linkage, limited to the file in which they are defined.
- Static local variables do not involve linkage, as their scope is limited to the local context.
Example:
Suppose there are two files: main.c and helper.c.
main.c
c#include<stdio.h> int g_var = 100; // Global variable void printHelper(); int main() { printf("In main: g_var = %d\n", g_var); printHelper(); return 0; }
helper.c
c#include<stdio.h> static int g_var = 200; // Static global variable void printHelper() { printf("In Helper: g_var = %d\n", g_var); }
In this case, since g_var in helper.c is static, it is a distinct variable from g_var in main.c. This means that when you run the program, it outputs:
shellIn main: g_var = 100 In Helper: g_var = 200
This clearly illustrates the differences in scope and linkage between static and non-static global variables.