Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 678
Jérôme Avatar asked May 17 '26 23:05

Jérôme


1 Answers

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.