cpp / beginner
Snippet
Namespaces: Avoiding Name Conflicts
A namespace groups related identifiers to avoid naming conflicts. Different namespaces can have variables or functions with the same name. Access items using the scope resolution operator (::). The std namespace contains standard library components like cout and endl.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>namespace math {int result = 42;}namespace text {int result = 100;}int main() {std::cout << math::result << std::endl;std::cout << text::result << std::endl;return 0;}
Breakdown
1
namespace math { int result = 42; }
Defines a namespace called math containing a variable result with value 42
2
std::cout << math::result << std::endl;
Accesses result from the math namespace using the scope resolution operator