I have 2 queries on rand() function usage in C++:
cout<<rand()<<endl;
in a loop and I didnt include any header file
except <iostream>
.. How did this work? In the reference examples I
came across in a few sites, some said, you need to include
<stdlib.h>
, others said,<time.h>
.. So wondering how my program worked..Any ideas?srand(time(NULL))
.. But again, I didnt do this in my simple program which just had cout<<rand()<<endl;
in a while loop and it was displaying random numbers.. So question: is srand(time(NULL))
used to improve randomness, as it's not mandatory? if not what could be the point of using it.Appreciate your help!
Thanks!
It is declared in <cstdlib>
header. Standard library headers (<iostream>
in you example) may include other standard headers, but you should not rely on that as it is implementation specific. Include the headers you need explicitly.
Seeding the random number generator is mandatory, unless you're happy with the fact that your program produces the same "random" sequence every time you run it :)
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