• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

srand call in C++. Once per function, class, file, program?

scootermaster

Platinum Member
Simple question: I have a function that needs to generate a random number every time its called. Do I call srand ( srand((unsigned)time(0)); )once in some early program-wide initialization, or do I need to call it per function call? I assume its global, but I just wanted to check.
 
srand() is a global C-language library routine.

If you control the entire codebase, find out if srand() is seeded anywhere else, and if so, use that seed. Elsewise, seed it yourself on the first call only.

By seeding only once, you'll produce a deterministic output for a given random seed (e.g., you could make the random seed a parameter if you ever want to reproduce the run).
 
srand() is a global C-language library routine.

If you control the entire codebase, find out if srand() is seeded anywhere else, and if so, use that seed. Elsewise, seed it yourself on the first call only.

By seeding only once, you'll produce a deterministic output for a given random seed (e.g., you could make the random seed a parameter if you ever want to reproduce the run).

Cool. That's what I figured. It's seeded now in the initialization of my driver file. Thanks!
 
Yes, I HIGHLY recommend having that seed being a parameter, stored in a config file, or some other input location for repeatability.
 
Back
Top