-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvariable_scope.cpp
More file actions
34 lines (27 loc) · 955 Bytes
/
variable_scope.cpp
File metadata and controls
34 lines (27 loc) · 955 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
using namespace std;
// -------- GLOBAL VARIABLE --------
// Declared outside all functions - accessible everywhere
int globalVar = 100;
void showScope() {
// -------- LOCAL VARIABLE --------
// Exists only inside this function
int localVar = 50;
cout << "Inside showScope() - localVar: " << localVar << endl;
cout << "Inside showScope() - globalVar: " << globalVar << endl;
}
int main() {
// -------- BLOCK SCOPE --------
int a = 10;
{
int b = 20; // b only exists inside this block
cout << "Inside block - a: " << a << ", b: " << b << endl;
}
// cout << b; // ❌ Error: b is out of scope here
// Accessing global variable
cout << "Inside main() - globalVar: " << globalVar << endl;
// Calling function to show local scope
showScope();
// cout << localVar; // ❌ Error: localVar not accessible here
return 0;
}