Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query on rand() function in C++

Tags:

c++

random

I have 2 queries on rand() function usage in C++:

  1. Where is rand() function defined ? I wrote a simple program to 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?
  2. I had heard before using "rand()", one needs to initialize by giving a seed to srand, and typically the seed is current unix time -> 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!

like image 595
user2715307 Avatar asked Aug 25 '13 11:08

user2715307


1 Answers

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 :)

like image 55
jrok Avatar answered Oct 05 '22 23:10

jrok