Nidal
Nidal

Reputation: 1883

rand() function in C return the same value

I have written a simple code with C

#include <stdio.h>
#include <stdlib.h>
int main()
{
int val = rand();
printf("val = %d",val);
}

and I have written a simple bash (to compile and execute the past C programme)

gcc test.c
gcc -o test test.c
./test

the problem is when ever I execute the bash it always returns the same value :val = 1804289383
How can I make it return random values as expected ??

Upvotes: 1

Views: 1424

Answers (1)

simonc
simonc

Reputation: 42175

Given the same starting point, repeated calls to rand will always generate a predictable stream of values. The way you change this is by seeding the generator with a value which varies. You do this by calling srand.

Assuming you don't need to run your program more than once a second, the current time would be a cheap/easy way of choosing a seed.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
    srand(time(NULL));
    int val = rand();
    printf("val = %d\n",val);
}

I've made another small change to your program. Output is sometimes line buffered so I've added a newline \n character to the end of your printf string.

Upvotes: 10

Related Questions