This comment, which states:
srand(time(0));
I would put this line as the first line in main() instead if calling it multiple times (which will actually lead to less random numbers).
...and I've bolded the line which I'm having an issue with... repeats common advice to call srand
once in a program. Questions like srand() — why call only once? re-iterate that because time(0)
returns the current time in seconds, that multiple calls to srand
within the same second will produce the same seed. A common workaround is to use milliseconds or nanoseconds instead.
However, I don't understand why this means that srand
should or can only be called once, or how it leads to less random numbers.
Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), and the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.
phoxis's answer to srand() — why call only once?:
Initializing once the initial state with the seed value will generate enough random numbers as you do not set the internal state with srand, thus making the numbers more probable to be random.
Perhaps they're simply using imprecise language, none of the explanations seem to explain why calling srand
multiple times is bad (aside from producing the same sequence of random numbers) or how it affects the "randomness" of the numbers. Can somebody clear this up for me?