Why does rand() compile without including cstdlib or using namespace std?

前端 未结 3 1700
终归单人心
终归单人心 2020-12-11 03:49

According to the book I\'m reading, rand() requires #include in C++
However, I am able to compile the following code that uses

相关标签:
3条回答
  • 2020-12-11 04:05

    iostream may include cstdlib directly or indirectly. This brings std::rand() and ::rand() in the scope. You are using the latter one.

    But yes, you should not count on this and always include cstdlib if you want to use rand. And in C++ code don't use rand, there are better ways to generate random numbers.

    0 讨论(0)
  • 2020-12-11 04:14

    You definitely should use the relevant include file for what you are using in your code. It saves you from surprises when you update the compiler/libraries to the new version. I think adding std:: in front of rand is a much better idea than to use using namespace std; - but either way, it's a good idea to NOT rely on it existing without a namespace, although that tends to be the way it works in most places to allow backwards compatibility for C-code.

    0 讨论(0)
  • 2020-12-11 04:16

    There are two issues at play:

    1. Standard library header files may include other standard library header files. So iostream may include cstdlib directly or indirectly.
    2. Header files with C-standard library equivalents (e.g. cstdlib) are allowed to bring C standard library names into the global namespace, that is, outside of the std namespace (e.g. rand.) This is formally allowed since C++11, and was largely tolerated before.
    0 讨论(0)
提交回复
热议问题