According to the book I\'m reading, rand()
requires #include
in C++
However, I am able to compile the following code that uses
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.
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.
There are two issues at play:
iostream
may include cstdlib
directly or indirectly.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.