tags:

views:

1390

answers:

4

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?

+1  A: 

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();
}
Eclipse
A: 

If I do,

srand(2);
srand(2);

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

prefer to either edit your question or comment on your own question over "answering" your own question like you did here.
Evan Teran
+2  A: 

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.

Raymond Martineau
A: 

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.

brian