C++ Programming/Code/Standard C Library/Functions/rand

From Wikibooks, open books for an open world
Jump to navigation Jump to search

rand[edit | edit source]

Syntax
#include <cstdlib>
int rand( void );

The function rand() returns a pseudo-random integer between zero and RAND_MAX. An example:

srand( time(NULL) );
for( i = 0; i < 10; i++ )
  printf( "Random number #%d: %d\n", i, rand() );

The rand() function must be seeded before its first call with the srand() function - otherwise it will consistently return the same numbers when the program is restarted.

Note:
The generation of random numbers is essential to cryptography. Any stochastic process (generation of random numbers) simulated by a computer, however, is not truly random, but pseudorandom; that is, the randomness of a computer is not from random radioactive decay of an unstable chemical isotope, but from predefined stochastic process, this is why this function needs to be seeded.

Related topics
srand