Srand () scope in C ++

When you call srand() inside a function, is that just the seed of rand() inside that function?

Here is the main function where srand() called.

 int main(){ srand(static_cast<unsigned int>(time(0))); random_number(); } void random_number(){ rand(); } 

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

So my question is: if you populated rand() with srand() , can you use seeded rand() outside of where srand() was called? Including functions, various files, etc.

+6
source share
2 answers

srand acts globally, we can see this by going to the draft C99 standard , we can refer to the C standard because C ++ is returning to the C standard for the functions of the C library, and it says (my attention):

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

It does not limit its effect to the area in which it was used, it just says that it calls subsequent calls to rand

The portable implementation example presented in the draft standard makes it more clear that the effect is global:

 static unsigned long int next = 1; void srand(unsigned int seed) { next = seed; } 
+9
source

No, it is used all over the world. This is not limited to function, not even to stream.

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

+7
source

Source: https://habr.com/ru/post/975853/


All Articles