CKTIS / C
srand — seed the rand generator
srand seeds the pseudorandom sequence produced by rand. Reusing the same seed repeats the sequence within an implementation.
Version: C23; repository compiler flag, production runtime not attested
Syntax
#include <stdlib.h>
void srand(unsigned int seed);srand, declared in <stdlib.h>, takes an unsigned int seed and returns nothing (void). It sets the sequence for subsequent rand() calls; it does not itself generate a number. Without an earlier srand, rand behaves as though srand(1) had been called.
The same seed repeats the sequence, but the actual numbers are not portable across implementations. Usually seed once before generating, rather than before every call. Randomness quality is not guaranteed: do not use this pair for cryptography. The standard also does not guarantee avoidance of data races between calls to these functions.
Examples
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int first[3];
srand(42u);
for (int i = 0; i < 3; ++i) {
first[i] = rand();
}
srand(42u);
for (int i = 0; i < 3; ++i) {
if (first[i] != rand()) {
puts("FAIL");
return 1;
}
}
puts("OK");
return 0;
}Result
OK
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.