In C, variables can have different scopes: local (inside a block), global (throughout the file), and file scope (static). Proper management of scopes is important for predictable behavior and preventing name conflicts.
Visible in all functions of the file, and if declared with extern, throughout the project.
Created upon entering a block (e.g., a function or loop). Not visible outside the block of declaration.
static int foo; — only for the current file.
Example:
static int counter = 0; // Only inside the file void increment() { int temp = 10; // local variable ++counter; }
If a global and a local variable have the same name, which one is used inside the function and why?
Answer: The local one is used, as it "shadows" the global name within its scope. The global variable remains accessible outside the declaration block of the local variable.
Example:
int value = 5; void foo() { int value = 10; printf("%d", value); // will print 10, not 5 }
Story
Story
static was forgotten for a helper function and variable, leading to name conflicts during linking and also to unpredictable errors during the assembly of different parts of the project.Story
There were cases where global variables were used in multithreaded code without proper synchronization. Due to implicit scope and inattentiveness when modifying values in different threads, data races occurred.