You'll often see two different styles for using things from the C++ standard library:
using namespace
In our introductory lessons, we add a using namespace std;
statement near the top of our files:
#include <iostream>
using namespace std;
int main() {
cout << "Hello\n"; // no std:: needed
string name{"World"}; // no std:: needed
}
std::
We can remove this, and instead use the std::
prefix any time we want to use a capability from the C++ standard library:
#include <iostream>
int main() {
// explicitly showing these come from std
std::cout << "Hello\n";
std::string name{"World"};
}
Both styles work perfectly fine, but there are good reasons why many developers prefer using std::
.
std::
Code Clarity:
Avoiding Naming Conflicts:
#include <string>
namespace game {
class string {}; // our own string class
}
int main() {
// clearly using std::string
std::string text{"Hello"};
// clearly using our string
game::string gameText{};
}
Professional Practice:
Remember: For this course, either style is fine - just be consistent within each program. As you progress to larger projects, you'll develop a preference based on your needs and team standards.
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