What are Namespaces?
A namespace provides a solution for preventing name conflicts in large projects. Imagine you are working on a team, and you and another developer both create a function called print()
. How does the compiler know which one to use?
Namespaces solve this by acting like a "last name" for your code. The functions and variables in the C++ Standard Library are all in a namespace called std
.
That's why we've been writing std::cout
and std::string
. We are telling the compiler to use the cout
and string
that belong to the std
namespace.
The using
Directive
Writing std::
everywhere can be tedious. To avoid this, you can use a using
directive. By writing using namespace std;
at the top of your file, you tell the compiler that you are using the std
namespace.
After that, you can write `cout` instead of `std::cout`.
#include <iostream>
// This line brings all names from std into the current scope
using namespace std;
int main() {
cout << "No std:: needed!";
return 0;
}
Note: While convenient, using this directive in large projects is sometimes discouraged because it can re-introduce the name-conflict problem it was designed to solve. For our small programs, however, it's perfectly fine!
Your Task
The code in the editor uses cout
and string
but is missing the `using` directive. Add `using namespace std;` after the `#include` lines to fix the code.
🎉
Lesson Complete!
Excellent! You now understand namespaces and how to use the `using` directive.
Back to Curriculum