Seeding the generator with srand
What you'll learn: How to use the current time to ensure your program generates a unique set of random numbers every time it runs.
The problem with "Fake" randomness
In C, the rand() function doesn't actually create numbers out of thin air. Instead, it follows a pre-written list of numbers that look random. Imagine a giant book filled with millions of digits. Every time you call rand(), the computer reads the next entry in that book.
By default, the computer always starts on page one, line one. This is why if you run a program that rolls a die, you might get a 4, 2, and 5. If you close the program and run it again, you will get 4, 2, and 5 again. This is great for debugging, but terrible for a game!
Enter the Seed
To fix this, we use srand() (short for "seed random"). Think of the "seed" as the starting page number for our book of random digits. If we give srand() a different number every time the program starts, rand() will start at a different point in its list, giving us a different result.
The most common way to get a "random" seed is to use the current system time. Since the time (in seconds) is always changing, your program will never start at the same point twice.
How to use it
To use the system time, you need to include <time.h>. You should call srand() exactly once at the very beginning of your main() function.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// 1. Seed the generator using the current time
// We cast it to 'unsigned int' because that is what srand expects
srand((unsigned int)time(NULL));
// 2. Now rand() will produce different results each run
printf("Random number: %d\n", rand());
printf("Another one: %d\n", rand());
return 0;
}
Common Pitfalls
A common mistake is putting srand() inside a loop. If you re-seed the generator every time you want a new number, and the loop runs fast (in less than a second), the time won't have changed yet. You’ll end up resetting the "book" to the exact same page over and over, resulting in the same number repeating! Always seed once at the start, and then let rand() do the work.
Key takeaway
Use srand(time(NULL)); once at the start of your program to ensure your random numbers stay unpredictable every time the code runs.