static and random generator in c++

1.4k views Asked by At
#include <iostream>
#include <random>

int gen_ran(void)
{
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_int_distribution<int> dist(0, 9);
    return dist(gen);
}

int main()
{
    for (int i = 0; i < 50; i++)
    {
        std::cout << gen_ran() << " ";
        if ((i + 1) % 10 == 0)
            std::cout << std::endl;
    }
}

I don't quite understand why we may put a static in each one of the three lines in the gen_ran() function. I googled a lot but it seems there are no clear answers.

My understanding is by using a static, we only initialize the objects once but the algrithms within each class (random_device, mt19937, uniform_int_distribution) can still generate random numbers. So static can save some computer resources when the function is called many times?

How about if I don't use any static or use one or two in the code. Does it make any difference if I don't in each case? Thanks very much.

1

There are 1 answers

0
Bathsheba On

The statements starting with static are executed only once and that happens when program flow first reaches the statements. That has the effect of setting up the generator exactly once, which includes the seeding.

If you don't make them static, then the random sequence would be reinitialised on every call of gen_ran() which would be a misuse of the generator.