srand() scope in C++
Asked Answered
P

2

9

When you call srand() inside of a function, does it only seed rand() inside of that function?

Here is the function main where srand() is called.

int main(){
    srand(static_cast<unsigned int>(time(0)));

    random_number();
}

void random_number(){
    rand();
}

The function random_number where rand() is used is outside of where srand() was called.

So my question is - If you seed rand() by using srand(), can you use the seeded rand() outside of where srand() was called? Including functions, different files, etc.

Propolis answered 25/9, 2014 at 19:15 Comment(0)
A
12

srand is in effect globally, we can see this by going to the draft C99 standard, we can reference to C standard because C++ falls back to the C standard for C library functions and it says (emphasis mine):

The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.

It does not restrict its effect to the scope it was used in, it just says it effects subsequent calls to rand

The example of a portable implementation provided in the draft standard makes it more explicit that the effect is global:

static unsigned long int next = 1;

void srand(unsigned int seed)
{
   next = seed;
}
Archiphoneme answered 25/9, 2014 at 19:23 Comment(0)
G
8

No, it applies globally. It is not limited to the function, not even to the thread.

cplusplus.com has more information: http://www.cplusplus.com/reference/cstdlib/srand/

Grillo answered 25/9, 2014 at 19:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.