Sobes.tech
Junior — Middle

What is the difference between a standard global variable and a static variable in terms of scope and lifetime?

sobes.tech AI

Answer from AI

A global variable in C/C++ is declared outside all functions and is accessible in all files if declared with external linkage (extern). The lifetime of a global variable is from the start of the program until it terminates.

A static variable can be of two types:

  1. File-level static variable (static global) — declared outside functions with the static keyword. It is visible only within this file (limited to the file scope), but its lifetime is from start to end of the program.

  2. Function-local static variable (static local) — declared inside a function with static. It retains its value between function calls but is only visible within that function. Its lifetime is from program start to end, but its scope is local.

Example:

int global_var = 0;          // global variable, visible in all files
static int file_static_var;  // static file variable, visible only in this file

void func() {
    static int func_static_var = 0; // static local variable
    func_static_var++;
}

Summary:

  • Global variable: visible in all files (if extern), lifetime — entire program.
  • Static file variable: visible only in the file, lifetime — entire program.
  • Static local variable: visible only within the function, lifetime — entire program.