C: srand has no effect on the 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;
}
As I understand it, this should print a different random number every time I run the program because the random seed depends on the system time.
But every time I run the program, I get exactly the same output:
1804289383
I still get the same result when I put custom values as an argument to srand:
srand(1);
or
srand(12345);
Does anyone have any idea why this is happening? Could it be because of my operating system (Mac OS 10.10.3)? Or the compiler I'm using (gcc)?
Are there simple alternatives?
source to share
So your problem is with multiple ways of generating random numbers in C with the standard libraries.
Basically, there are two sets of functions for generating 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 a random (3) guide:
#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 just have to choose the one that suits you best. I invite you to take a closer look at these guides for more information; -)
source to share
The standard random number generator in C is equal rand()
, which can be visited with srand(seed)
.
There is a second random number generator random()
. This random generator can be seeded with a function srandom(seed)
. (These two generators use separate states, even though they use the same implementation.)
So, just pick the right pair of seeding and RNG functions.
source to share