rand() is a PRNG (a "pseudo random number generator")
It basically is a formula which takes an input number 'n', does a series of mathematical computations on the number to "scramble" it, then gives 'n' back as a "random" number, and also uses 'n' for the next iteration of rand().
A simplistic version of rand would be this (note: rand is likely more complicated... and this prng is very crappy. It's just conceptual):
1 2 3 4 5 6 7
|
int rand_state = 0;
int rand()
{
rand_state = (rand_state * 15675461) + 18836753;
return rand_state;
}
|
Notice that if you call rand(), since the input is 0 the first time... you will get the same output every time since the result of that formula will always be the same.
To solve this problem... you can "seed" the prng, which gives it a new starting point. The function for this is srand(). Conceptually, srand() looks something like this (again, this is oversimplified):
1 2 3 4
|
void srand(int seed)
{
rand_state = seed;
}
|
The usage here is that you would call srand() once at the start of your program with a unique seed. This gives the prng a unique starting point, and will allow rand to generate a different stream of numbers every time.
A typical usage is to use the current time as the seed. Since the system time will be different every time the user runs the program.... it ensures they will have a unique seed.
EDIT: Of course I'm ninja'd by a shorter, more direct answer. But I still feel the above info is useful.