I know this is a weird question, but I would really like to know what's behind the srand() function, just out of sheer curiosity. Is it possible to write a C code that has the same end or is it dependent on the machine itself? thank you for your help. XP
srand()
is a function.
The details of its implementation can vary greatly from one implementation to another, but the ISO C standard provides a sample implementation of both srand
and rand
. See N1570 section 7.22.3:
static unsigned long int next = 1;
// RAND_MAX assumed to be 32767
int rand(void)
{
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}
void srand(unsigned int seed)
{
next = seed;
}
It's important to note that this is not in any sense the implementation of the rand
and srand
functions; it's just one possible implementation, provided by the standard as an example.
Note that the sequence of "random" (actually pseudo-random) numbers resulting from calls to rand()
, for a given seed passed to srand()
is fixed. This is deliberate; it allows you to reproduce the same behavior for a program by using the same seed. These functions are typically not suitable for applications that require high-quality pseudo-random numbers.
For more information, see the excellent comp.lang.c FAQ, particularly questions 13.15 through 13.21.