capypad
0 day streak
cpp / beginner
Snippet

Organizing Code with Namespaces

Namespaces organize code into logical groups, preventing name conflicts. Think of them as containers that hold related functions and variables. The :: (scope resolution) operator accesses items inside a namespace. You can also use 'using namespace' to avoid typing the prefix repeatedly in a scope.

snippet.cpp
cpp
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
#include <iostream>
 
namespace math {
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
}
 
namespace text {
void greet() {
std::cout << "Hello from text namespace!\n";
}
}
 
int main() {
std::cout << "5 + 3 = " << math::add(5, 3) << std::endl;
std::cout << "5 * 3 = " << math::multiply(5, 3) << std::endl;
text::greet();
using namespace math;
std::cout << "Using add directly: " << add(10, 20) << std::endl;
return 0;
}
Breakdown
1
namespace math {
Declares a namespace called 'math' to group arithmetic functions together
2
int add(int a, int b) {
Function inside the math namespace, adds two integers and returns the result
3
namespace text {
A separate namespace for text-related functions, keeping names distinct
4
math::add(5, 3)
Calls the add function using the scope resolution operator to specify which namespace it belongs to
5
using namespace math;
Allows direct access to all names in math namespace without the :: prefix within this scope