Scope, Lifetime & Namespaces
Scope: where a name is visible
- Block scope: declared inside
{ }, visible until the closing brace - Function parameters: visible in the function body
- Global scope: declared outside all functions, visible everywhere after
- Shadowing: an inner variable with the same name hides the outer one ⚠️ (confusing — avoid)
int x = 1;
{
int x = 2; // shadows the outer x
} // inner x destroyed here
Lifetime: how long it exists
| Kind | Created | Destroyed |
|---|---|---|
| Automatic (local) | when declaration runs | at end of block |
static local | first time the line runs | when program ends (keeps value between calls) |
| Global | before main | after main |
Dynamic (new) | new | delete (Unit 7) |
Namespaces
A namespace groups names to avoid collisions:
namespace budget {
double total = 0;
void add(double x) { total += x; }
}
budget::add(500);
::is the scope resolution operator::xrefers to the global x- Namespaces can be nested:
namespace app::ui { ... }(C++17)
using
using std::cout; // using-declaration: just one name ✅
using namespace std; // using-directive: brings in EVERYTHING ⚠️
Why using namespace std; is discouraged
stdcontains thousands of names (count,distance,max,data, …) that can clash with yours- Never put it in a header file
- Fine in tiny practice programs; prefer
std::or using-declarations in real code
Anonymous namespaces
namespace { int helper; } → visible only in this .cpp file (like static in C).
Namespace aliases
namespace fs = std::filesystem;
Example
#include <iostream>
int counter = 100; // global
namespace budget {
double total = 0;
void add(double amount) { total += amount; }
}
namespace savings {
double total = 0; // same name, different namespace: no clash
void add(double amount) { total += amount; }
}
int visits() {
static int count = 0; // keeps its value between calls
return ++count;
}
int main() {
budget::add(1500);
budget::add(800);
savings::add(5000);
std::cout << "budget::total = " << budget::total << ", savings::total = " << savings::total << '\n';
int counter = 5; // shadows the global counter
std::cout << "local counter = " << counter << ", global counter = " << ::counter << '\n';
{
int temp = 42; // lives only inside this block
std::cout << "temp inside block = " << temp << '\n';
}
// std::cout << temp; // error: temp is out of scope
visits();
visits();
std::cout << "visits() called " << visits() << " times\n";
using std::cout; // using-declaration for one name
cout << "Using cout without std::\n";
return 0;
}
/* Output:
budget::total = 2300, savings::total = 5000
local counter = 5, global counter = 100
temp inside block = 42
visits() called 3 times
Using cout without std::
*/