How to deal with static storage duration warnings?
Using global variables is problematic, and it is common wisdom to avoid them unless they're absolutely necessary. For details, see:
Are global variables bad?
Your question title also regards non-global-scope static storage duration variables (e.g. static locals of functions); these are less problematic but can also give you some headaches, especially in multi-threaded work.
Bottom line: It's best to make your functions depend only on their parameters and have as few side-effects as is necessary. Let's do this with your getNumber()
function:
template <typename Distribution>
typename Distribution::result_type getNumber (
std::default_random_engine& random_engine,
Distribution& distribution)
{
return distribution( random_engine );
}
int main()
{
std::default_random_engine engine( static_cast<unsigned int>( time(nullptr) ) );
std::uniform_int_distribution<unsigned int> randomInt( 1, 6 );
for ( unsigned int counter = 1; counter <= 10; ++counter ) {
std::cout << std::setw( 10 ) << randomInt( engine );
if ( counter % 5 == 0 )
std::cout << std::endl;
}
std::cout << getNumber( engine, randomInt ) << std::endl;
return 0;
}
One way to defer initialization of global variables such as the ones you are using is to wrap them in get
-functions.
std::default_random_engine& getEngine()
{
// Initialized upon first call to the function.
static std::default_random_engine engine(static_cast<unsigned int>(time(nullptr)));
return engine;
}
std::uniform_int_distribution<unsigned int>& getRandomInt()
{
// Initialized upon first call to the function.
static std::uniform_int_distribution<unsigned int> randomInt(1, 6);
return randomInt;
}
and then use getEngine()
and getRandomInt()
instead of using the variables directly.