Search code examples
cmacosrandomsrand

C: srand does not influence random number generator


I have the following c code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[]) {
  srand(time(NULL));
  printf("%d\n", (int)random());
  return 0;  
}

To my understanding, this should print a different random number every time I execute the program because the random seed is dependent of the system time.

But every time run the program, I get exactly the same output:

1804289383

I still get the same output when I put custom values as argument for srand:

srand(1);

Or

srand(12345);

Does anyone have an Idea why this happens? Maybe it is because of my operating system (Mac OS 10.10.3)? Or the compiler I use (gcc)?

Are there simple alternatives?


Solution

  • Well, your problem here is due to multiple way of making random numbers in C with the standard libraries.

    Basically, there is two sets of functions to generate a random number :

    From the rand(3) manual:

       #include <stdlib.h>
    
       int rand(void);
       int rand_r(unsigned int *seedp);
       void srand(unsigned int seed);
    

    From the random(3) manual:

       #include <stdlib.h>
    
       long int random(void);
    
       void srandom(unsigned int seed);
    
       char *initstate(unsigned int seed, char *state, size_t n);
       char *setstate(char *state);
    

    You should just pick the one that suit the best your need. I invite you to further read those manuals for more information ;-)