-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnameSpace.cpp
More file actions
31 lines (24 loc) · 1.11 KB
/
nameSpace.cpp
File metadata and controls
31 lines (24 loc) · 1.11 KB
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
#include <iostream>
// A namespace in C++ is a declarative region that provides
// a scope for identifiers such as variables, functions, classes, and other entities.
// It is used to organize code into logical groups and to prevent name collisions.
namespace Math {
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
}
int main() {
// We don't need to use std::cout, std::endl if we do:
// Doing this brings all names from the std namespace into the current scope.
// using namespace std;
// Doing this brings only the name cout and endl from the std namespace into the current scope not all names.
using std::cout;
using std::endl;
// :: = scope resolution operator
int result = Math::add(2, 3); // Accessing add() from Math namespace
cout << "Result: " << result << endl;
// using namespace = allows us to use the identifiers without the scope resolution operator
using namespace Math;
int result2 = subtract(2, 3); // Accessing subtract() from Math namespace
cout << "Result2: " << result2 << endl;
return 0;
}