This code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
printf ("First number: %d\n", rand() % 100);
srand ( time(NULL) );
printf ("Random number: %d\n", rand() % 100);
srand ( 1 );
printf ("Again the first number: %d\n", rand() %100);
return 0;
}
has the following output:
First number: 41
Random number: 13
Again the first number: 41
There is also the following rule:
Two different initializations with the same seed, instructs the pseudo-random generator to generate the same succession of results for the subsequent calls to rand in both cases.
I understand the words but I just don’t understand the method itself. Why did it return 41 again? Is it random or must it return the same result in every case according to this code?
If you call
rand()without first callingsrand(), the behavior is as if you calledsrand()with1as the argument.This behavior is defined in the original C standard. I don’t have a full copy of it handy, but The Open Group’s POSIX standards are the next best thing, as they incorporate the full C standard (with some extensions):
http://www.opengroup.org/onlinepubs/000095399/functions/rand.html
The actual result of a
rand()call for any given seed is implementation-defined, except that for any seed x, call n torand()after the seeding of the generator must return the same result. So while on your implementation you will always get 41 on the firstrand()call after callingsrand(1), and you will always get the same result (whatever it is) for the secondrand()call, other implementations may use a different algorithm that produces different results.