Search code examples
crandomsrand

why does NULL of srand (time (NULL)) give time () a random value?


In C language, use srand (time (NULL)); can produce random numbers from 0 to 32767. My question is, why does NULL of srand (time (NULL)) give time () a random value?

Also, how to generate random numbers over 32767?

Use

if (rand ()% 2 == 0) {ans = rand () + (0b1 << 15);}
else {ans = rand ();}

Is it suitable?


Solution

  • Regarding "why does NULL of srand (time (NULL)) give time () a random value?"

    Check the man page of time(), it mentions

    time() returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). If t is non-NULL, the return value is also stored in the memory pointed to by t.

    In this usage, we need only the return value, and we don't need to store that value additionally in any buffer, so we pass NULL as argument. Also, the returned value is not random, it's the number of seconds since the Epoch, 1970-01-01. So every invocation updates the value (strictly incremental).

    That said, regarding the range of values returned by calling rand()

    The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]).

    Check the value of RAND_MAX in your platform.

    That said, rand() is a poor PRNG, you can check this thread for better ways to get yourself a random number.