Does stdlib’s rand() always give the same sequence?

Yes, given the same environment for the program. From the C standard §7.20.2.2/2,

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.

Of course, this assumes it is using the same implementation detail (i.e. same machine, same library at the same execution period). The C standard does not mandate a standard random number generating algorithm, thus, if you run the program with a different C standard library, one may get a different random number sequence.

See the question Consistent pseudo-random numbers across platforms if you need a portable and guaranteed random number sequence with a given seed.

Leave a Comment