Imagine a long line of "pseudo-random" numbers. There's a pointer to some place in the line and calling rnd()
prints out the number being pointed to and moves the pointer to the next number. The next call to rnd()
does the same thing. Unless two of the same numbers happen to be right next to one another, which can happen but is unlikely, you'll get two different numbers for two different calls to rand. When you call srand
you basically set the pointer to a known point on the line so calls to rnd()
will return what they did before.
In pictures:
srand(0)
... 1 9 3 4 9 7 ...
^ (srand puts the pointer to 9.)
a call to rand returns 9 and updates the pointer:
... 1 9 3 4 9 7 ...
^
the next call to rnd() will return 3.
If you call srand(0) again it'll be
... 1 9 3 4 9 7 ...
^
and a call to rnd() will return 9 again.
If you want to keep the same "random" number call rnd
once and save the value until you need it again rather than calling rnd each time.