Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

rand — pseudorandom integers

rand() returns a pseudorandom integer. srand() lets you reproduce a sequence within an implementation.

Version: C23; repository compiler flag, production runtime not attested

Syntax

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

rand() from <stdlib.h> returns an int from 0 through RAND_MAX, inclusive; RAND_MAX is at least 32767.

srand(seed) restarts the sequence: the same seed reproduces it within an implementation, not necessarily across implementations. Without srand(), the sequence is as for srand(1).

Randomness quality is not guaranteed: do not use rand() for cryptographic secrets. The functions rand() and srand() need not prevent data races between their calls.

Examples

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    srand(42u);
    int first = rand();
    srand(42u);
    int repeated = rand();
    printf("%d\n", first == repeated);
    return 0;
}

Result

1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources