Names specified here
Name Description Notes Source Availability
RAND_MAX Maximum of random range M <stdlib.h> C89 C90 C95 C99 C11
rand() Generate pseudo-random number (·) <stdlib.h> C89 C90 C95 C99 C11
srand() Seed random-number generator (·) <stdlib.h> C89 C90 C95 C99 C11

<stdlib.h> declares functions for generating sequences of pseudo-random numbers.

#include <stdlib.h>
int rand(void);

rand returns the next random number in the sequence, in the range zero to RAND_MAX, which is at least 32767. If you want an integer in a specific range [a, b), you should scale it to the correct range:

double random_unif_r01(void)
{
  return rand() / (RAND_MAX + 1.0);
}

int random_unif_iab(int a, int b)
{
  return random_unif_r01() * (b - a) + a;
}

rand may have reasonably uniform distribution, but there may be platform-specific alternatives with better statistical properties.

POSIX, BSD and SVID define random to yield 32-bit pseudo-random numbers.

#include <stdlib.h>
void srand(unsigned seed);

srand re-seeds the sequence using the provided argument. The initial seed is 1.

An effective and portable way to randomize the initial seed is to use the current time:

#include <stdlib.h>
#include <time.h>
srand(time(NULL));

However, this technique and the use of rand in general are not suitable for cryptography.


CHaR
Sitemap Supported
Site format updated 2024-06-05T22:37:07.391+0000
Data updated 1970-01-01T00:00:00.000+0000
Page updated 2022-06-17T21:43:05.000+0000