At the following: http://www.fredosaurus.com/notes-cpp/misc/random.html
It mentions that if we want to generate a random number in the range 1-10
, we ca
rand()
returns an int
in the range [0, RAND_MAX
]. rand() % 10
returns an int
in the range [0,9] because non-negative x modulo k is at most k-1. Adding 1 shifts the range to [1,10].
(The results from rand() % k
are not guaranteed to be uniformly distributed. Even if you patch that up, this is really a poor man's way of generating random numbers and not recommended for generating crypto keys and the like. A stronger RNG library is part of Boost.)
srand(time(0))
takes the current time in the hope that the user executes the program at random times. If the program is executed at time t and t + 1s, the random number generator will make sure it returns very different results. If you don't seed it, you're likely to get the same results every time. I'm not sure what the C standard has to say about this, though. In any case, if you seed once in an application that runs for a long time, rand()
eventually starts repeating itself.
(This in turn is the poor man's way of seeding the RNG. On Linux or BSD, read from the special file /dev/random
to get "real" random seeds. Alternatively, check if your operating system can return the time with at least microsecond granularity.)