I understand that rand() function generates the same number(s) each you run it if you don't change the seed number. That's where srand() comes in. Time is always changing so I know that you should pass the time(null) parameter to srand. My question is with the code below from a tutorial site.
int main()
{
int i, n=5;
time_t t;
/* Intializes random number generator */
srand((unsigned) time(&t));
/* Print 5 random numbers from 0 to 50 */
for( i = 0 ; i < n ; i++ ) {
printf("%d\n", rand() % 50);
}
return(0);
}
I see no link from the srand
((unsigned) time(&t));
and rand.
printf("%d\n", rand() % 50);
Where is the connection between rand and srand? What I mean or expect is I assume rand() will get some parameter from srand() so it knows to generate different numbers each time. I assume it would look something like rand(srand(time(null));
It's like initializing a variable without using it to me. srand is being initialized, but I don't see it being used.
Does rand generate different numbers because srand is called first before rand?
man 3 rand
andman 3 srand
. – Fitzgerald