srand - scope of its effects/are they global?

J

jdm

Hi,

I'm writing a program which will use rand() to generate some random
numbers and srand plus time(0) to seed the PRNG. This raised a
question: if I use srand in one function (eg main) which then calls
another function in which the calls to rand() are made, will the
reseeding I did in the calling function affect rand()'s behaviour?

Or do I need to use srand() at the start of every function in which I
use rand?

(In other words, what is the scope of a PRNG reseeding?)
--------------
//Example:

#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

void some_function(some parameters);

int main(int argc, char *argv[])
{
time_t random_seed = time(0);
if (seed == time_t(-1))
{
//do some error-handling
}
srand((unsigned int)random_seed);
some_function(parameters);

...

return 0;
}

void some_function(some parameters)
{
//do various things involving calls to rand()
}
-------------
Thanks,

James McLaughlin.

PS. I will probably replace the calls to rand() and srand() with
something from Boost later on, but I still thought this was worth
finding out in case a similar issue occurred in the future.
 
Ö

Öö Tiib

Hi,

I'm writing a program which will use rand() to generate some random
numbers and srand plus time(0) to seed the PRNG. This raised a
question: if I use srand in one function (eg main) which then calls
another function in which the calls to rand() are made, will the
reseeding I did in the calling function affect rand()'s behaviour?

Or do I need to use srand() at the start of every function in which I
use rand?

srand() will seed pseudo-random-generator of standard library. That
means everywhere in your program that uses rand() of same standard
library. That usually means everywhere. However there exist eccentric
cases when modules of same program manage to link themselves to
different standard libraries.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top