Seeding the Random Number Generator with the Current Time

To randomize without having to enter a seed each time, we may use a statement like

srand( static_cast<unsigned int>( time( 0 ) ) );

This causes the computer to read its clock to obtain the value for the seed. Function time (with the argument 0 as written in the preceding statement) typically returns the current time as the number of seconds since January 1, 1970, at midnight Greenwich Mean Time (GMT). This value (which is of type time_t) is converted to an unsigned int and used as the seed to the random number generator—the static_cast in the preceding statement eliminates a compiler warning that’s issued if you pass a time_t value to a function that expects an unsigned int. The function ...

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.