Scope determines where a variable is visible and accessible in your code. A variable exists only within the block where it was declared. Step outside that block and the variable ceases to exist.
Local vs Global Scope
A variable declared inside a function is local — only that function can see it. A variable declared outside all functions is global — every function in the file can access it. Global variables are tempting but they make code harder to reason about.
#include <iostream>
int globalCount = 100;
void show() {
int localNum = 42;
std::cout << "Global: " << globalCount << "\n";
std::cout << "Local: " << localNum << "\n";
}
int main() {
show();
globalCount = 200;
std::cout << "Updated global: " << globalCount << "\n";
return 0;
}
globalCount is accessible from both show()
and main(). But localNum only exists inside
show() — trying to use it in main() would
cause a compile error.
Block Scope
In C++, a block is anything inside curly braces {}. A
variable declared inside a block is only visible within that block.
This includes if, for, and while
blocks:
#include <iostream>
int main() {
int x = 10;
if (x > 5) {
int y = 20;
std::cout << "Inside block: x=" << x << ", y=" << y << "\n";
}
std::cout << "Outside block: x=" << x << "\n";
return 0;
}
y is created when the if block starts and
destroyed when it ends. This is useful for keeping temporary variables
contained and avoiding accidental reuse.
Scope Resolution
If a local variable has the same name as a global variable, the local
one takes precedence inside that function. You can still access the
global one using the scope resolution operator :::
#include <iostream>
int value = 50;
int main() {
int value = 10;
std::cout << "Local value: " << value << "\n";
std::cout << "Global value: " << ::value << "\n";
return 0;
}
The ::value syntax tells the compiler to look for the
global value, ignoring the local one. This is a good
trick to know, but shadowing variables like this usually confuses
readers — it is better to just use different names.