Topic 36 of 83
Scope
Overview
Scope determines where a variable is accessible and how long it lives. Local variables die when the block ends. Global variables live for the entire program. Static local variables live for the entire program but are only accessible in their local block.
Syntax
cpp
int globalVar = 10; // Accessible anywhere
void counter() {
int localVar = 0; // Recreated every call
static int statVar = 0; // Created once, persists across calls
localVar++;
statVar++;
}Common Pitfalls
- Shadowing: Declaring a local variable with the exact same name as a global variable, which hides the global one.
- Overusing global variables makes code hard to test, debug, and trace.
Interview Tips
- Be able to explain exactly what `static` does inside a function. It changes the lifetime from 'automatic' (stack) to 'static' (data segment), meaning it retains its value between function calls.
Real-World Example
Using static variables to track how many times a function is called.
example
cpp
#include <iostream>
using namespace std;
void generateID() {
static int currentID = 1000; // Only runs the first time
currentID++;
cout << "Generated ID: " << currentID << endl;
}
int main() {
generateID(); // 1001
generateID(); // 1002
generateID(); // 1003
return 0;
}