srand() — Set seed for rand() function


Standards / Extensions C or C++ Dependencies

Single UNIX Specification, Version 3



#include <stdlib.h>

void srand(unsigned int seed);

General description

srand() uses its argument seed as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand(). If srand() is not called, the rand() seed is set as if srand(1) was called at program start. Any other value for seed sets the generator to a different starting point. The rand() function generates pseudo-random numbers.

Some people find it convenient to use the return value of the time() function as the argument to srand(), as a way to ensure random sequences of random numbers.

Returned value

srand() returns no values.


/* CELEBS31                                      

   This example first calls &srand. with a value other than 1 to                
   initiate the random value sequence.                                          
   Then the program computes 5 random values for the array of                   
   integers called ranvals.                                                     
   If you repeat this code exactly, then the same sequence of                   
   random values will be generated.                                             
#include <stdlib.h>                                                             
#include <stdio.h>                                                              
int main(void)                                                                  
   int i, ranvals[5];                                                           
   for (i = 0; i < 5; i++)                                                      
      ranvals[i] = rand();                                                      
      printf("Iteration %d ranvals [%d] = %d\n", i+1, i, ranvals[i]);           
Iteration 1 ranvals [0] = 24107
Iteration 2 ranvals [1] = 16552
Iteration 3 ranvals [2] = 12125
Iteration 4 ranvals [3] = 9427
Iteration 5 ranvals [4] = 13152