Reputation: 11
Recently i've noticed that if I don't include the 'using namespace std' in my program and just use 'std::cout' or 'std::endl' then my program still compiles just fine? Therefore if I use the 'std::' prefix is it even necessary to include the 'using namespace std'? Does the 'std::' prefix call the using namespace std? If someone can clear this up for me it would be greatly appreciated.
Upvotes: 1
Views: 944
Reputation: 73
When you use:
using namespace std;
You're telling the program that anything that it can't find should be in the namespace std. For larger programs, this is a problem because you might be using multiple namespaces with functions that have the same name, so it's best to use std::cout
for larger programs.
Upvotes: 0
Reputation: 7463
In C++, ::
is called the "scope resolution operator", so std::cout
means "The variable cout
, which can be found inside std
".
The using namespace std;
directive means "For any name you can't find, also try looking it up in std
". Thus, if you explicitly say std::cout
(and equivalent for everything else in the std
namespace), then you don't need using namespace std
.
As others have said, it's usually considered bad style to use using namespace std;
, because a lot of the names in std
are things you might want to use elsewhere, for example std::count
. A compromise option is to instead say using std::cout;
, which will tell the compiler to look for cout
in std
but not anything else.
There's debate about whether to say using std::cout
or just write std::cout
everywhere you need it in your main C++ file, but most people believe that you should rarely if ever use using namespace
. If you're writing a header file, though, you should never use a using
directive at the top level because then every file which includes yours will get it, and they might want to use different names.
Upvotes: 6