cpp / beginner
Snippet
Namespaces: Organizing Your Code
Namespaces help organize code into logical groups, preventing name conflicts. Instead of one giant pile of functions and variables, you can group related items together. The :: operator (scope resolution) lets you access items inside a namespace. This is especially useful when working on larger projects or using libraries that might have overlapping function names.
snippet.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
#include <iostream>using namespace std;namespace MathTools {double PI = 3.14159;double circleArea(double radius) {return PI * radius * radius;}}namespace StringTools {string repeat(string text, int times) {string result = "";for (int i = 0; i < times; i++) {result += text;}return result;}}int main() {cout << MathTools::circleArea(5) << endl;cout << StringTools::repeat("Ha", 3) << endl;return 0;}
Breakdown
1
namespace MathTools {
Creates a namespace grouping math-related code together
2
MathTools::circleArea(5)
Calls function from the MathTools namespace using ::
3
StringTools::repeat("Ha", 3)
Calls function from the StringTools namespace