atb
atb

Reputation: 963

How to get a random number every time a function is called in C

So I'm making a game that needs to generate a random number every time the attack function is called. For every run of the program it generates a a different one, I think this is because I use srand(time(NULL)); however, if I attack more than once, the it returns the same number that I already called. Here is a sample of my random function at the moment.

srand(time(NULL));
int attrand = rand() % 16;

How can I make it return a different number every time it is called within the same execution of the program?

Upvotes: 1

Views: 2914

Answers (1)

MByD
MByD

Reputation: 137322

Move the seed initialization to some init function, and keep only int attrand = rand() % 16; in this function.

void my_init() {
    srand(time(NULL));
}

int get_random() {
    return rand() % 16;
}

Upvotes: 8

Related Questions