E
E
Eugene Ordinary2020-08-09 21:48:34
C++ / C#
Eugene Ordinary, 2020-08-09 21:48:34

How is rand() organized?

As I understand it, the rand() function has some kind of local static variable that remembers the previous call. But how does this variable interact with the srand() initialization function? Can I somehow declare a static variable shared by two functions? Or is there just a global variable in the module?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AnT, 2020-08-10
@TheCalligrapher

You described everything absolutely correctly: a function rand()is a stateful function, i.e. it has a state that persists between successive function calls. And for obvious reasons, this state should also be available to the function srand().
However, in the first place, it is not clear why you decided that this state must be stored in a local static variable declared inside the rand(). Even if you follow your logic, it is much more reasonable to assume that this is some kind of static variable declared at the file (module) level, and immediately available to both the function rand()and the functionsrand(). Or even a global variable. (In many implementations of the standard library that try to support multithreaded applications, this state can be stored in a thread-local variable.
) relation to C or C++. It can be implemented in Assembler, Fortran or in the language of Nanai boys. Only its external interface should be compatible with C or C++, not its internal implementation. Therefore, to consider the implementation of the standard library in terms of C or C++ is a meaningless and incorrect exercise. The implementation of the standard library lives by its own laws. If she needs the state rand()to be also available insrand()- so it will be. And how it's done is the magic of a specific implementation.

V
Vladimir Korotenko, 2020-08-09
@firedragon

If you want random, take something normal. And preferably iron.
What OS?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question