C++ Variable Scope: Local vs Global

Variable scope defines where a variable can be accessed in the program. In C++, variables can have local or global scope, affecting their visibility and lifetime.

1. Local Variables

Local variables are declared inside a function or block and can only be accessed within that function or block.

  • Scope: Limited to the function/block in which they are declared.
  • Lifetime: Exists only during function execution.
  • Stored in: Stack memory.
C++
Example of local variables
#include <iostream>
using namespace std;

void demoLocal() {
    int localVar = 10; // Local variable
    cout << "Local variable: " << localVar << endl;
}

int main() {
    demoLocal();
    // cout << localVar; // Error: localVar not accessible here
    return 0;
}

2. Global Variables

Global variables are declared outside all functions and are accessible from any function in the same file (or across files using extern).

  • Scope: Entire program (or file if static).
  • Lifetime: Exists throughout the program execution.
  • Stored in: Data segment.
C++
Example of global variable
#include <iostream>
using namespace std;

int globalVar = 100; // Global variable

void display() {
    cout << "Global variable: " << globalVar << endl;
}

int main() {
    display();
    globalVar = 200;
    display();
    return 0;
}

3. Local vs Global Variable Conflict

If a local variable has the same name as a global variable, the local variable overrides the global variable inside its scope.

C++
Example of scope conflict
#include <iostream>
using namespace std;

int num = 50; // Global variable

int main() {
    int num = 100; // Local variable shadows global
    cout << "Local num: " << num << endl;   // Prints 100
    cout << "Global num: " << ::num << endl; // Use :: to access global (50)
    return 0;
}

4. Best Practices

  • Use local variables whenever possible to avoid side effects.
  • Minimize global variables to improve maintainability.
  • Use descriptive names to prevent conflicts.
  • Use static keyword for file-scope globals if needed.

5. Complete Demonstration Program

C++
Program demonstrating local and global variables
#include <iostream>
using namespace std;

int globalCounter = 0; // Global variable

void incrementLocal() {
    int localCounter = 0; // Local variable
    localCounter++;
    cout << "Local Counter: " << localCounter << endl;
}

void incrementGlobal() {
    globalCounter++;
    cout << "Global Counter: " << globalCounter << endl;
}

int main() {
    incrementLocal(); // Prints 1
    incrementLocal(); // Prints 1 again (new local variable each call)

    incrementGlobal(); // Prints 1
    incrementGlobal(); // Prints 2 (global value persists)

    return 0;
}

Conclusion

Understanding local and global variable scope is crucial in C++. Local variables provide temporary storage and prevent unintended side effects, while global variables persist across the program. Proper usage ensures maintainable and bug-free code.