I have a C++ application which calls rand() in various places. Do I need to initialize srand()
regularly to ensure that rand() is reasonably random, or is it enough to call it once when the app starts?
Only once, at the start of your application. Save this answer.
srand seeds the pseudorandom number generator. If you call it more than once, you will reseed the RNG. And if you call it with the same argument, it will restart the same sequence.
The generation of the pseudo-random number depends on the seed. If you don't provide a different value as seed, you'll get the same random number on every invocation(s) of your application. That's why, the srand() is used to randomize the seed itself.
In general, libraries should never call srand . The call to srand should be made once, usually in main , and is the responsibility of the application. Any other solution ends up with multiple libraries competing with each other.
If you have only a single thread, seed once. If you reseed often, you might actually break some of the statistical properties of the random numbers. If you have multiple threads, don't use rand
at all, but rather something threadsafe like drand48_r
, which lets you maintain a per-thread state (so you can seed once per thread).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With