The rand
function generates some sequence of numbers. (The sequence is calculated but is intended to serve as if the numbers were random, so they are called pseudo-random.) By itself, it will always generate the same sequence of numbers in a program. We use srand
to choose which sequence of numbers it generates. (Most commonly, rand
generates a cycle of the same numbers, if called enough times, and srand
merely chooses where in that cycle we start.)
So, you call srand
to set the starting point of the sequence for rand
. The value you pass to srand
is any unsigned int
value. In the C standard, there is no specified meaning for the value. You just give srand
a number like 1 to get one sequence, 2 to get a different sequence, 3 to get another sequence, and so on. You have no other control over the actual values generated; setting the seed to some particular value does not guarantee the first rand
call will return any particular documented value.
The C standard also does not specify any method for calculating the numbers in the sequence. Each C implementation may choose its own method. Some C implementations use bad methods, in which the numbers are not very random-like at all, and some patterns can be easily observed. (For this reason, it is often recommended to use alternatives, like Unix’s srandom
and random
.)
When a program is being debugged or is being used as a class assignment, it is common to call srand
with a fixed value, like srand(2020)
. This results in rand
generating the same numbers each time. That makes it easier to debug the program or to check the results of student programs. When varying sequences of numbers are designed, it is common to call srand
with srand(time(NULL))
. Assuming the time is available (time(NULL)
may return −1 for an error), this causes the program to use different sequences at different times. (Commonly, the value of time
as an integer changes once per second, but this can vary depending on the C implementation.)