Skip to content

Commit 52614e6

Browse files
committed
add 013_VarScopes_and_Namespace.cpp
1 parent b215cfe commit 52614e6

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

013_VarScopes_and_Namespace.cpp

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
// Memory Segments
5+
// https://ozh.github.io/ascii-tables/
6+
7+
// +--------+------------------------------------------+
8+
// | FFFFh | |
9+
// | | |
10+
// | Static | Local variables |
11+
// | | Parsed arguments to function |
12+
// | | Recursive function call |
13+
// +--------+------------------------------------------+
14+
// | | |
15+
// | Heap | |
16+
// | | Dynamically allocated variables/memory |
17+
// +--------+------------------------------------------+
18+
// | | Initialized variable Local/Global |
19+
// | | |
20+
// | |------------------------------------------+
21+
// | Data | |
22+
// | | .bss (uninitialized variables) |
23+
// | | global, static, extern variables |
24+
// | | Note: not occupying but only in .obj file|
25+
// +--------+------------------------------------------+
26+
// | | |
27+
// | | |
28+
// | Text | compiled program |
29+
// | | Machine code |
30+
// | 0000h | Crt.o (startup routine |
31+
// +--------+------------------------------------------+
32+
33+
34+
35+
namespace MyNamesapce {
36+
int a, b;
37+
long int lnNum = 10;
38+
int sum(int num1, int num2){
39+
return num1+num2;
40+
}
41+
}
42+
43+
// variable scopes
44+
int x = 55; //global scope
45+
void increment (int num){
46+
cout << "Increment " << num << " by 1 = " << ++num << endl;
47+
// increment(++num); // stack overflow, cz function pointers and local
48+
// variables are stored in stack
49+
}
50+
51+
int main(int argc, char const *argv[]) {
52+
cout << "using only \"cout\" instead of \"std::cout\"" << '\n';
53+
cout << "MyNamesapce::lnNum = " << MyNamesapce::lnNum << endl;
54+
// access namespace items
55+
using namespace MyNamesapce;
56+
cout << "lnNum = " << MyNamesapce::lnNum << endl; //scope resolution operator not req.
57+
cout << "sum of 5 + 7 = " << sum(5,7)<< '\n';
58+
// namespace aliasing
59+
namespace NewName = MyNamesapce;
60+
cout << "sum of 5 + 7 = " << NewName::sum(5,7)<< '\n';
61+
62+
// Scope of variables
63+
cout << "x = " << x << '\n';
64+
int x = 5; // local scope
65+
{
66+
int x = 10; // inner scope
67+
cout << "x = " << x << '\n';
68+
}
69+
cout << "x = " << x << '\n';
70+
71+
// stackoverflow error
72+
increment(1);
73+
return 0;
74+
}

0 commit comments

Comments
 (0)