According to the book I'm reading, rand()
requires #include <cstdlib>
in C++
However, I am able to compile the following code that uses rand()
without #include <cstdlib>
nor using namespace std;
in Visual Studio 2015.
Why are these two not needed to compile? Should I include cstdlib?
C++ Code:
#include <iostream>
int main()
{
std::cout << rand() << std::endl;
}
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 .
rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.
why is it compulsory to use using namespace std ? It isn't. In fact, I would recommend against it. However, if you do not write using namespace std , then you need to fully qualify the names you use from the standard library.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With