The short answer
Use the std:: prefix by default. It works everywhere and shows where each name comes from. If you are asking when to use std :: in C++, that is the starting point. A using declaration for a few names suits some files, and the directive suits small practice programs.
Where the prefix is the safe default
- Headers. Many files include a header, so anything it declares should be clear without a directive.
- Shared and library code. Other people read it, and may include it in projects that have their own names.
- Code you are unsure about. When in doubt, the prefix is easy to read and hard to get wrong.
Here is a small header that uses the prefix:
// greet.h
#ifndef GREET_H
#define GREET_H
#include <string>
std::string greet(const std::string& name);
#endif
Where a using declaration fits
A using declaration brings in one name. It works well in a source file that uses the same few names many times:
// greet.cpp
#include "greet.h"
using std::string;
string greet(const string& name) {
return "Hello, " + name;
}
string here is the same type as std::string, so the definition matches the declaration in the header. Only string comes into view. Other standard names still need the prefix.
Where the directive is acceptable
A using directive is reasonable in a single-file practice program, where you are the only reader and the code is short. Inside a function body, it applies only to that function, which limits the effect.
Avoid it in headers. A directive there reaches every file that includes the header, and that is the main reason to keep it out.
Quick reference
| Option | Example | Best for |
|---|---|---|
| std:: prefix | std::cout << x; |
headers and shared code |
| using declaration | using std::cout; |
a few names in a source file |
| directive inside a function | using namespace std; inside a function body |
short practice code |
| directive at file level | using namespace std; at the top of a file |
single-file learning programs |
Making the choice
Ask two questions. Will other files include this code? If yes, use the prefix or a using declaration. Will only you read it? If yes, the directive is a fair choice.