Search code examples
c++randomrandom-seedsrand

Why does rand() produce different numbers in a loop despite srand() being set once at the beginning of the program?


I made a program that produces a different random number 10 times.
Here is the code:

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    srand(time(0));
    for (int i = 0; i <10; i++) {
        
        std::cout << rand() % 100 << std::endl;
    }
    return 0;
}

It runs fine. However, I do not understand why. I did some research and based on what I understand:

  • rand() is always seeded to 1, which therefore produces the same number
  • In order to generate different results, I have to seed it with something different(like the time) by doing this : srand(time(0))

My concern is: if I set the seed once outside the loop, shouldn't rand() produce the same number? Because based on what I know, rand() gives pseudo-random numbers, which are "fake", and I understood that it follows a certain predictable algorithm, which means that in every iteration of the loop it uses the same seed set outside the loop which is supposed to give me the same numbers. Why would I get different numbers?


Solution

  • srand() is seeding the random generator.
    This means that for every seed there will be a sequence of pseudo random values that the generator can produce (not a single value).
    Every call to rand() will return the next value in the sequence.

    The documentation explicitly mentions that:

    Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), at the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.

    Therefore calling srand() once is not only OK in your case, it is actually the recommended way.

    A side note:
    In C++ is it recommended to use <random> instead of the lagacy rand().
    See more info here: How to generate a random number in C++?.