A: Have you ever written some really killer C program -- such as a game -- that uses the rand() random number function, only to find that it seemingly isn't random after all? The problem isn't in rand() per se, but in the fact that it needs to be reseeded before use. What to seed it with? Why, a random number of course!
If you find this circular logic confusing, don't worry. The standard C library has just the function you need to provide a suitable seed for initializing the rand() function every time you start your program. Simply call the time() function and use it as the seed value! Simply by adding the one following line to your program, your random numbers will become truly random once again.
srand(((unsigned int)time(NULL)) | 1);
This is pretty straightforward, but you may be asking why OR the time with 1? The rand() and srand() functions are used to, respectively, access and seed a pseudo random number generator (RNG). Since the RNG is based on an algorithm, it's obviously not truly random (that's why it's called a pseudo-RNG). If you keep supplying it with the same seed using the srand() function, you'll get the same sequence of numbers when you call the rand() function. Nowadays, most RNGs in most compiler libraries are pretty good, but this wasn't always so and still isn't guaranteed. As it turns out, the randomness of an RNGs output may be influenced by whether the seed is odd or even. Since odd seeds are generally better in such instances, OR'ing the output with 1 may cut the available range of seed values in half, but it does help assure better quality results.
All that having been said, feel free to experiment with it. It may well be that your compiler's RNG is good enough not to need it. For more information, see section 7.20.2 in the ISO/IEC C standard (also referenced by the C++ standard).
- Determining a file's size
- Rounding floating-point values
- Sorting an array of strings
- Computing the wind chill factor
- Timers and default actions
- Getting a string of arbitrary length
All the code in C Snippets is either public domain or freeware and may therefore freely be used by the C programming community without restrictions. In most cases, if the original author is someone other than myself he or she will be identified. Thanks to all who have contributed to this collection over the years. I hope Dr. Dobb's readers will find these useful.