This is the so-called. "frequent error".
If the program code contains multiple attempts to "restart" a pseudo-random number generator, using as a seed value the current time value obtained by calling time(NULL)
... srand(time(NULL)); ...
it may happen that such calls to srand
will follow each other very quickly. So fast, that time(NULL)
will return the same time value. This will lead to the fact that the pseudo-random number generator will constantly restart with the indication of the same seed value. As a result, subsequent rand()
calls will produce the same pseudo-random sequence.
For example, the following code, being executed, will most likely output the same pseudo-random sequence two times.
#include <stdlib.h> #include <stdio.h> #include <time.h> int main() { srand(time(NULL)); for (unsigned n = 20; n > 0; --n) printf("%d ", rand()); printf("\n"); srand(time(NULL)); for (unsigned n = 20; n > 0; --n) printf("%d ", rand()); printf("\n"); }
This problem is also sometimes reported in the following form: "Under the debugger I have different random numbers in my program, and without the debugger, the same ones." Indeed, when the program is executed step-by-step in an interactive debugger, it runs “slowly” and between calls to the srand
time value time(NULL)
time to change, which creates the illusion that everything works “as intended”. But it is worth running the program into free execution, as the problem manifests itself in all its glory.
If you need a srand(time(NULL))
call in your program, in most cases it is enough to do it only once at the start of the program.