Search code examples
c++randomsrand

srand() scope in C++


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.


Solution

  • 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;
    }