1
#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.

Ethan
  • 161
  • 2
  • 9
  • Please open you C++ student book and try find chapter what `static` means in a scope of a function (note it has different meaning in global scope). – Marek R Oct 08 '21 at 10:20
  • I've read about this over the last few days and but still not clear. I feel the static used in this case is relating to initialize an object and keep it there untill the end of the program? Not a static variable within the scope of a function? Or everything is the same basically since everything is treated as an object generally in c++? Thanks again! – Ethan Oct 08 '21 at 11:00
  • `static` has many different flavours depending on context. It's really the answer to the quest of minimising the number of keywords in C and C++. In the context of your program, `static` initialises the variable the first time program control encounters it. Conceptually, once initialised, it survives the closing brace of `main`. – Bathsheba Oct 08 '21 at 11:13

1 Answers1

5

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483