0

I use this function to generate random integer.

int rnd(int min, int max)
{
    static int srand(time(0));
    return min + rand() % max;
}

Is it right? May be better to move srand(time(0)); to the main function? Like this:

int rnd(int min, int max){
    return min + rand() % max;
}
int main(){
srand(time(0));
..............
}
Orange Fox
  • 147
  • 7

4 Answers4

3

Definitely. You are now not calling the function but creating an integer variable named srand instead which shadows the global srand().

It does not help to re-seed the random generator each time -- it would even return always the same value if called during the same second! Calling it just once in main() would be better.

Also it should probably be min + rand() % (max - min + 1).

Yirkha
  • 12,737
  • 5
  • 38
  • 53
3

Your first version does not do what you intend:

int rnd(int min, int max)
{
    static int srand(time(0));
    return min + rand() % max;
}

This does not call the function srand. It declares a static variable of type int and assigns it the value of time(0). Like int a(42); (or in C++11 int a{42};) declares an integer and sets it to 42.


Definitely use the second variant. It also makes live much easier, if you want to have another function for creating random values in a different way.


Additionally I strongly recommend to use std::random (or boost::random if you are not allowed to use C++11 for some obscure reason).

Danvil
  • 22,240
  • 19
  • 65
  • 88
1

In general you only need to initialize the pseudorandom number generator once, so in the main function is a good idea.

I believe Netscape once had a bug due to seeding the random number generator too often, which caused its SSL implementation to be more easily cracked.

tfinniga
  • 6,693
  • 3
  • 32
  • 37
1

Is it right?

If by that you mean "is it generating a random number?", the answer is yes.

If you mean "is it optimal?" then the answer is no. You only need to initialize the sequence of random number once.

May be better to move srand(time(0)); to the main function

Maybe ... (you know what you need better than us).

What are you trying to achieve (that is, what are you using this random generator for)? If it is anything with financial data, online gambling application (or anything that takes/manages/costs money) it is not ok (nor is it to use srand and rand - you need something stronger).

utnapistim
  • 26,809
  • 3
  • 46
  • 82