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

Getting a unique seed with `time(NULL)`

Getting a unique seed with time(NULL)

What you'll learn: How to use the current system time to ensure your random number generator produces different results every time you run your program.

The problem with a fixed seed

In C, the rand() function isn't truly random; it follows a pre-determined formula. If you provide the same starting point—called a seed—using srand(), the formula will spit out the exact same sequence of "random" numbers every time. If you write srand(1);, your game or simulation will be identical every single time it starts. To fix this, we need a seed that changes every second.

Using the clock as a spark

The most common way to get a unique seed is to look at the system clock. C provides a function called time() (found in the <time.h> header) that returns the Unix timestamp. This is a large integer representing the total number of seconds that have passed since January 1, 1970.

Think of it like a massive, invisible stopwatch that never stops ticking. Because the time is always moving forward, the value returned by time(NULL) will be different every time you hit the "Run" button on your code.

Putting it into code

To use this, you pass time(NULL) directly into srand(). You only need to do this once at the very beginning of your main() function.

#include <stdio.h>
#include <stdlib.h> // Required for srand() and rand()
#include <time.h>   // Required for time()

int main() {
    // 1. Get the current time and use it to seed the generator
    srand(time(NULL));

    // 2. Now rand() will produce a different sequence each run
    int random_num = rand() % 100;
    
    printf("Random number (0-99): %d\n", random_num);

    return 0;
}

How it works

When you call srand(time(NULL)), you are telling the computer: "Look at the clock, take the current second, and use that number to scramble the starting point of your random formula."

If you run the program at 12:00:01 PM, you get one sequence. If you run it again at 12:00:02 PM, the seed has changed, and you get a completely new sequence. The only catch is that if you run the program twice within the same second, the seed will be the same, and the "random" results will match. For most beginner programs, however, this is the perfect way to create the illusion of true randomness.

Key takeaway

Use srand(time(NULL)); once at the start of your program to ensure your random numbers change every time you run your code.