capypad
0 day streak
cpp / beginner
Snippet

Namespaces: Avoiding Name Conflicts

Namespaces organize code into named groups to prevent naming conflicts. The same identifier can exist in different namespaces without collision. Use the scope resolution operator (::) to access namespace members. The std namespace contains standard library components.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
 
namespace math {
int multiply(int a, int b) {
return a * b;
}
}
 
namespace text {
int multiply = 5;
}
 
int main() {
std::cout << "math::multiply(4, 3) = " << math::multiply(4, 3) << std::endl;
std::cout << "text::multiply = " << text::multiply << std::endl;
return 0;
}
Breakdown
1
namespace math { }
Defines a namespace called 'math'
2
namespace text { }
Defines a separate namespace called 'text'
3
math::multiply(4, 3)
Accesses multiply function from math namespace
4
text::multiply
Accesses multiply variable from text namespace