Today, I noticed that the same random number is being generated every time in a specific part of a program I am working on. My assumption was that it wasn't getting seeded properly, but it appears that it is.
I reduced the issue down to the simplest code possible. Here it is:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main()
{
srand(time(0));
printf("%d\n", rand() % 49);
return 0;
}
Every time I run this program, it prints the number 13. If I change the 49 the random number is getting mod-ed by to a 50 or a 48, I get a random sequence as expected (by running the program repeatedly). However, my program (the real one, not the example above) relies on an asset that for the time-being will always cause the variable that rand() is mod-ed by to be 49.
Am I missing something or doing something incorrectly? Is there something wrong with the hardware device on my processor that generates pseudo-random numbers? How can I get my program to generate a different random number (one that does not divide by 49 with a remainder of 13) each time?
EDIT:
I recognize that time(0) only changes once per second. I have run this program multiple times and not in the same second, so that is not the issue. I am running on macOS. The result is the same whether I compile with gcc-11 (from Homebrew) or clang. Turning optimizations on or off has no effect.
I tried running the program a few times without the modulo to generate a sequence. Here are the numbers that were generated: 862706704, 862723511, 862740318, 862757125, 862773932, 862824353. Those all happen to divide by 49 to leave a remainder of 13.