Search code examples
crandomsrand

Does the srand function work over multiple translation units?


If I call srand in my main function, would it also affect results in my functions in other translation units?


Solution

  • Some small information from the source code of glibc.

    srand is a weak alias for __srandom. (Source).

    __srandom calls __srandom_r (Source).

    __srandom_r is just updating the struct random_data passed to it, based on the seed. (Source)

    rand(void) is just calling __random. (Source).

    __random calls __random_r, passing the same structure, that was passed to __srandom_r. (Source).

    __random_r then generates a random value from the passed struct. (Source).

    So, to put it in a nutshell, a call to srand in your main-function will affect the random numbers in every other function, while your program runs, as the state is shared between all functions.