Understanding std::
Prefix
Why do some code examples online use std::cout
instead of just cout
?
You'll often see two different styles for using things from the C++ standard library:
Style 1: 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
}
Style 2: Explicit 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::
.
Benefits of Using std::
Code Clarity:
- It's immediately clear where things come from
- Helps when reading unfamiliar code
- Makes it easier to spot what features you're using
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:
- Many companies require this style in their coding standards
- It's common in open source projects
- Makes code more maintainable in large projects
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.
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