crandomlanguage-lawyerglibcsrand

Is it allowed for srand(0) to have the same effect as srand(1)?


Is it allowed for srand(0) to have the same effect as srand(1)?

C11, 7.22.2.2 The srand function (empahasis added):

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.

However, in glibc srand(0) has the same effect as srand(1):

  /* We must make sure the seed is not 0.  Take arbitrarily 1 in this case.  */
  if (seed == 0)
    seed = 1;

Hence, the same sequence of pseudo-random numbers is returned by subsequent calls to rand, which is confusing.

Extra: We see that in MSVC srand(0) does not have the same effect as srand(1).


Solution

  • "new sequence" in this case just means a freshly started sequence. Look at the next sentence in C11 §7.22.2.2p2:

    If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated.

    This means that srand(10); followed by srand(10); creates two new sequences that are guaranteed to be the same, so new doesn't mean "unique" in this context.

    Nothing is stopping srand(0) and srand(1) from also being the same sequence.