Understanding namespace std
Why do we need to write using namespace std; - what happens if we remove it?
The line using namespace std; is a convenience feature that lets us use things from the standard library without typing std:: before them. Let's see what happens when we remove it:
#include <iostream>
using namespace std;
int main() {
// won't compile without std::
cout << "Hello World!\n";
}error: 'cout' was not declared in this scopeTo fix this, we need to specify that we're using cout from the std namespace:
#include <iostream>
int main() {
// works fine with std:: prefix
std::cout << "Hello World!";
}Hello World!Why Namespaces Exist
Namespaces help prevent naming conflicts. Imagine two different libraries both have a function called print():
#include <iostream>
namespace printerLib {
void print() {
std::cout << "Printing document...\n";
}
}
namespace graphicsLib {
void print() {
std::cout << "Drawing to screen...\n";
}
}
int main() {
// we know exactly which print() to use
printerLib::print();
// no confusion about which one we mean
graphicsLib::print();
}Printing document...
Drawing to screen...Why Some People Avoid using namespace std
While using namespace std; is fine for learning and small programs, many developers prefer to explicitly write std:: because:
- It makes it clear where things come from
- It prevents potential naming conflicts in larger programs
- It's considered more professional style
You can also be selective about what you import:
#include <iostream>
using std::cout; // only import cout
int main() {
// cout works without std::
cout << "Hello World!";
// endl still needs std::
cout << std::endl;
}For this course, using using namespace std; is perfectly fine - just be aware that you'll see both styles in real-world code.
Setting up a C++ Development Environment
Getting our computer set up so we can create and build C++ programs. Then, creating our very first application