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 scope
To 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!
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...
using namespace std
While using namespace std;
is fine for learning and small programs, many developers prefer to explicitly write std::
because:
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.
Answers to questions are automatically generated and may not have been reviewed.
Getting our computer set up so we can create and build C++ programs. Then, creating our very first application