Problems when calling srand(time(NULL)) inside rollDice function

Lyrk picture Lyrk · Mar 22, 2013 · Viewed 11.7k times · Source

When I used at first srand(time(NULL)) in rollDice() function it did not work. But when I put it in main, it works. Why is that? Can you tell me the logic?

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

int rollDice(void) {
    return (1+rand()%6) + (1+rand()%6);
}
int main(void) {
    int roll;
    srand(time(NULL));          
    roll = rollDice();
    printf("You rolled %d.\n", roll);

    enum Gamestatus {WON,LOST,CONTINUE};
    enum Gamestatus status;

    while(status==CONTINUE){
        printf("You are rolling again: \n");
        printf("You rolled %d\n", roll = rollDice());

        if (targetPoint==roll){
            printf("You win!");
            status=WON;
        }
        else if(7==roll){
            printf("You lost!");
            status=LOST;
        }
        else
            status=CONTINUE;
    }
    return 0;
}

Answer

pmg picture pmg · Mar 22, 2013

Let's say you have millions of books with rows upon rows of random numbers. Before you get a random number you need to select a book.

After you have a book, to get random numbers, read numbers sequentially from the book. Changing the book gets another sequence of random numbers.
Changing to the same book restarts the sequence form the first number in the book.

srand() chooses a book and starts random numbers from the beginning
rand() reads the next number from the selected book

If you put srand() inside the loop, you are effectively restarting the random number sequence from the beginning of the same book.

Solution: select 1 book once, and keep reading numbers from it for ever and ever.

In a C program, if you don't "select a book", the random numbers come from book #1 or, in other words, in the absence of a srand() call, the function rand() behaves as if srand(1) has been called.