Why is rand () compiled without including cstdlib or using the std namespace?

According to the book I'm reading, rand() requires #include <cstdlib> in C ++
However, I can compile the following code that uses rand() without #include <cstdlib> and using namespace std; in Visual Studio 2015.
Why are these two not needed for compilation? Should I include cstdlib?

C ++ Code:

 #include <iostream> int main() { std::cout << rand() << std::endl; } 
+6
source share
3 answers

There are two problems in the game:

  • Standard library header files may include other standard library header files. Thus, iostream can include cstdlib directly or indirectly.
  • Header files with C-standard library equivalents (e.g. cstdlib ) are allowed to enter the names of the standard C library in the global namespace, i.e. outside the std (e.g. rand .) This is formally permitted with C ++ 11, and to a greater extent carried over earlier.
+7
source

iostream can include cstdlib directly or indirectly. This results in std::rand() and ::rand() . You are using the latter.

But yes, you should not rely on this and always include cstdlib if you want to use rand . And in C++ code does not use rand , there are more efficient ways to generate random numbers.

+4
source

You must use the appropriate include file for what you use in your code. This saves you from surprises when updating the compiler / libraries to the new version. I think adding std:: before rand is a much better idea than using using namespace std; - but in any case, it is a good idea NOT to rely on it, existing without a namespace, although it usually works like this in most places to provide backward compatibility for C code.

+2
source

All Articles