Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 678
Jorge Luque Avatar asked Mar 10 '16 07:03

Jorge Luque


People also ask

Do you need Cstdlib with Rand?

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 .

How rand() works in c++?

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.

Is it mandatory to use namespace std in C++?

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.


1 Answers

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.
like image 166
juanchopanza Avatar answered Oct 11 '22 15:10

juanchopanza