andrewL
andrewL

Reputation:

Will repeated calls to srand() in c++ use the same seed?

If I have srand(2) declared in my main of my driver file, do I need to declare srand(2) in my code file which is being linked with my driver?

Thanks.

edit

(from user's comment below)

If I do,

srand(2);
srand(2);

will I get the seed as 2? or something else?

Upvotes: 0

Views: 3522

Answers (3)

Brian
Brian

Reputation: 5966

When you call srand() with a particular seed, it begins the sequence for that seed regardless of any previous call to srand(). Every time you call srand(2) for example, subsequent calls to rand() will give you the same numbers in the same order every time. So:

srand(2);
srand(2);

is redundant. This link has a good description of srand.

Upvotes: 0

Raymond Martineau
Raymond Martineau

Reputation: 6039

srand(2) sets the seed of the random number generator to 2. Calling it again with the same parameter sets the seed to 2 again, and will cause the random generator to create the same output.

FYI, If the driver uses it's own copy of srand (i.e. it's a DLL), it might not affect the random generator used in your main executable.

Upvotes: 2

Eclipse
Eclipse

Reputation: 45533

I think you'll have to clarify your question a bit more, but in general, you have to declare (but not define) every function you use in a given translation unit. If you want to use srand in a .cpp file, you'll have to #include <stdlib.h> in that file.

For the usage of srand - take a look at its documentation. You'll usually only need to call it once in a given process, after which you can expect the same sequence of pseudo-random values each run. Calling it again with the same seed will restart the sequence of values. If you're wanting different values each run, try seeding with the current time.

EDIT:

Do you mean that you have two files something like this:

// Driver.cpp
#include <stdlib.h>
#include "otherfile.h"

int main()
{
    srand(2);
    Somefunc();
}

And then another file linked in:

// OtherFile.cpp
#include <stdlib.h>
#include "otherfile.h"

void SomeFunc()
{
    // You don't need to call srand() here, since it's already been called in driver.cpp
   int j = rand();
}

Upvotes: 1

Related Questions