rand function called from a static function

Hello all,
I have a class with a static method that calls the rand function. This class is instantiated several times, for any object I would like that rand generate a different random sequence. I have problems because the same random sequence is generated even I use srand method before calling rand. Is there some problem to call rand function inside a static function? Thanks. See the code above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int RandomInteger (int low, int high)
{
    srand (int(CURRENT_TIME));
    int k;
    double d;
    d = (double) rand () / ((double) RAND_MAX + 1);
    k = d * (high - low + 1);
    return low + k;
}

int MyClass::myStaticFunction (const void *a_, const void *b_)
{
  int r = RandomInteger (-1, 1);
  return r;
}

call...
1
2
 srand (int(CURRENT_TIME));
      qsort (entry, (numberOfElem), sizeof (entry[0]),  myStaticFunction);
Last edited on
Please edit your post and put the source inside code tags. It will make your post a lot more legible and folks here will be more likely to look at it.
This is a really common newbie mistake for some reason...

I have problems because the same random sequence is generated even I use srand method before calling rand.


The same random sequence is generated because you use srand before calling rand.

srand should be called exactly once -- at the very start of your program. That's it. You do not call it for each individual number you want generated. You do not call it for each object. You only call it once.


EDIT: it also looks like you're sranding with a constant -- which will guarantee that you get the same sequence every time...
Last edited on
Where you should and how you should seed:

1
2
3
4
5
6
7
8
9
10
11
#include <ctime>
#include <cstdlib>

// class definition

int main()
{
  std::srand( (unsigned) std::time(NULL) ); // Once, at beginning of main. Nowhere else.

// code here
}
It's true, thanks.

I was confused after reading this: http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

Now I undestood.

Thanks.
Topic archived. No new replies allowed.