Format
#include <stdlib.h>
int rand(void);
int rand_r(unsigned int *seed);
Language Level: ANSI
Threadsafe: No. rand() is not threadsafe, but rand_r() is.
Description
The rand() function generates a pseudo-random integer in the range 0 to RAND_MAX (macro defined in <stdlib.h>). Use the srand() function before calling rand() to set a starting point for the random number generator. If you do not call the srand() function first, the default seed is 1.
Return Value
The rand() function returns a pseudo-random number.
Example that uses rand()
This example prints the first 10 random numbers generated.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int x;
for (x = 1; x <= 10; x++)
printf("iteration %d, rand=%d\n", x, rand());
}
/********************* Output should be similar to: ************
iteration 1, rand=16838
iteration 2, rand=5758
iteration 3, rand=10113
iteration 4, rand=17515
iteration 5, rand=31051
iteration 6, rand=5627
iteration 7, rand=23010
iteration 8, rand=7419
iteration 9, rand=16212
iteration 10, rand=4086
*/
Related Information