Course contentsShow
← C
Lesson 886 of 1,21912. The Standard LibraryFree lesson

Why you should only seed once

Why you should only seed once

What you'll learn: Why calling srand() multiple times in a program leads to broken, repetitive "random" results instead of true unpredictability.

The Clock is the Key

In C, the rand() function doesn't actually create randomness out of thin air. It follows a complex mathematical formula to generate a sequence of numbers. To start this sequence, it needs a starting point called a seed, which we provide using srand().

Most programmers use the current system time—time(NULL)—as the seed. Since the time changes every second, your program gets a different starting point every time you run it.

The "Reset" Trap

A common mistake beginners make is placing srand(time(NULL)) inside a loop or a function they call frequently. Imagine you are reading a book of random numbers. Seeding is like choosing which page to start on. If you "re-seed" every time you need a new number, you are constantly flipping back to the start of a page.

Because computers are incredibly fast, they can execute thousands of lines of code in a single second. If you call srand(time(NULL)) inside a loop, the system time likely won't have changed yet. You end up resetting the random number generator to the exact same starting point over and over, resulting in the same "random" number being generated repeatedly.

Doing it the Right Way

You should call srand() exactly once at the very beginning of your main() function. This sets the "entry point" for the entire duration of your program.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    // 1. Seed ONCE at the start
    srand(time(NULL));

    // 2. Now call rand() as many times as you want
    for (int i = 0; i < 5; i++) {
        printf("Number %d: %d\n", i + 1, rand() % 100);
    }

    return 0;
}

By seeding once, you let the mathematical formula move forward naturally. Every time you call rand(), it moves to the next unique number in the sequence, ensuring your results look truly shuffled and unpredictable.

Key takeaway

Call srand() only once at the start of your program to prevent your "random" numbers from getting stuck in a repetitive loop.