Background:
Global and local variables were introduced in C to manage memory and code visibility. Global variables were once the primary means of sharing data between functions before modular programming emerged, while local variables allowed for reduced interaction and increased code isolation.
Problem:
There is often a misunderstanding of the difference between global and local variables: their lifetimes, scopes, rules, and timing of initialization. Global variables lead to problems with synchronization and readability, while local ones can result in the unavailability of required data. Misunderstandings about these differences can lead to bugs and hinder code scalability.
Solution:
Global variables are declared outside of all functions and are accessible in all files when using extern. Their lifetime spans the entire program, and initialization is performed either implicitly to zeros (for static variables) or explicitly with user-defined values. Local variables are declared within functions, their lifetime is limited to the function call, and their contents are not automatically initialized.
Code Example:
int g_var = 42; // Global variable void foo() { int l_var = 5; // Local variable }
Key Features:
Does a local variable automatically initialize to zero if no initial value is set?
No. Only global and static variables are initialized to zeros by default. Local variables contain "garbage" (undefined value) unless a starting value is explicitly set.
Example:
void test() { int a; printf("%d\n", a); // Undefined behavior }
Can a global variable always be accessed from different files?
No. If a variable is declared as static outside a function, it is only visible in that source file. If global visibility is needed, use extern.
Can a global variable be declared inside a function?
No. All declarations inside a function are local. Only outside functions can global variables be created.
A global variable is used for data exchange between functions:
int error_code; void f1() { error_code = 1; } void f2() { if (error_code) ... }
Pros:
Cons:
All variables are local, data is passed through function parameters:
void f1(int *err) { *err = 1; } void f2(int err) { if (err) ... }
Pros:
Cons: