Jérôme
Jérôme

Reputation: 27027

namespace usage

I'm trying to start using namespaces the correct (or at least best) way.

The first thing I tried to do was to avoid putting using namespace xxx; at the beginning of my files. Instead, I want to using xxx::yyy as locally as possible.

Here is a small program illustrating this :

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
   using std::cout;
   using std::endl;

   srand(time(0));

   for(int i=0; i<10;++i)
      cout << rand() % 100 << endl;

   return 0;
}

If I omit the lines using std::cout; or using std::endl, the compiler will complain when I'm trying to use cout or endl.

But why is this not needed for srand, rand and time ? I'm pretty sure they are in std, because if I try to specifically pour std:: in front of them, my code is working fine.

Upvotes: 3

Views: 461

Answers (4)

Serge
Serge

Reputation: 7694

As long as we on the subject, there's also a thing called Koenig Lookup which allows you to omit a namespace identifier before a function name if the arguments it take come from the same namespace.

For example

#include <iostream>
#include <algorithm>
#include <vector>

void f(int i){std::cout << i << " ";}
int main(int argc, char** argv)
{
   std::vector<int> t;
   // for_each is in the std namespace but there's no *std::* before *for_each*
   for_each(t.begin(), t.end(), f); 
   return 0;
}

Well, it's not related directly but I though it may be useful.

Upvotes: 0

anon
anon

Reputation:

If you use cstdlib et al. the names in them are placed in both the global and the std:: namespaces, so you can choose to prefix them with std:: or not. This is seen as a feature by some, and as a misfeature by others.

Upvotes: 6

Stowelly
Stowelly

Reputation: 1270

I prefer to omit using and just have the std::cout every time just to maintain readability. although this is probably only useful in larger projects

Upvotes: 3

xtofl
xtofl

Reputation: 41509

If you really want to know, take a close look at the ctime and cstdlib headers. They were built backwards-compatible.

Note: all this using vs. using namespace business is about readability. If your IDE would allow to just not show the namespaces when you don't want to see them, you wouldn't need these constructs...

Upvotes: 3

Related Questions