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

scootermaster

Platinum Member
Nov 29, 2005
2,411
0
0
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.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
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).
 

scootermaster

Platinum Member
Nov 29, 2005
2,411
0
0
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!
 

Fallen Kell

Diamond Member
Oct 9, 1999
6,154
504
126
Yes, I HIGHLY recommend having that seed being a parameter, stored in a config file, or some other input location for repeatability.