Search code examples
c++randomoverloadingambiguous

Why does random() work in cstdlib? (Ubuntu 10.10)


I always thought the random functions in cstdlib were only rand and srand, but the following works (compiled with g++ on Ubuntu 10.10)?

I actually found this out when moving from Windows to Ubuntu, my compilation failed as it was ambiguously overloading (I had declared my own 'random()' function).

#include <cstdlib>
#include <iostream>

using namespace std;

int main() {
 srandom(50);
 cout << random();
 return 0;
};

Also the following compiles correctly on Ubuntu, it appears after checking stdlib.h, that the random() and srandom(), among others, are not declared in the std namespace. Which makes it a complete pain in the arse...

#include <iostream>
#include <cstdlib>

int main() {
    std::cout << random();
    return 0;
};

Solution

  • Because compiler writers are free to add extra things to the language library to make your job easier. Normally, it wouldn't be a problem, because it puts them in a namespace which you won't be adding things to, std.

    Your problem arises from that little line

    using namespace std;
    

    This pulls everything from std into your program's namespace, including std::random, which the compiler writers helpfully provided. If you instead explicitly declare what you're pulling from std, you wouldn't clobber your local random with std::random:

    using std::rand;
    using std::srand;
    

    See also this question from the c++ FAQ lite.