开发者

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

I always thought the random functions in cstdlib were only rand开发者_StackOverflow中文版 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;
};


random() is part of the Single Unix Specification. It’s not part of the C++ Standard. That’s why it’s not on Windows but is found on most Unix/Mac platforms.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜