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.
The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1) were called at program start. Any other value for seed sets the generator to a different starting point. The rand() function generates the pseudo-random numbers.
No, it applies globally. It is not limited to the function, not even to the thread.
The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.
The generation of the pseudo-random number depends on the seed. If you don't provide a different value as seed, you'll get the same random number on every invocation(s) of your application. That's why, the srand() is used to randomize the seed itself.
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;
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With