If I don't specify srand(), what seed does rand() use?
Asked Answered
S

5

8

Here is the code:

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

int main(void)
{
    int r;
    int i;
    for (i = 0; i < 100; i++)
    {
        r = rand() % 100 + 1;
        printf("%d\n", r);
    }
    return 0;
}

I've been trying to random number but one day, I forgot to put srand() in, but the rand() function can still random a number (the same sequence).

The question is, what seed does it use if I don't specify it?

Steradian answered 10/1, 2013 at 5:36 Comment(0)
A
9

If srand is not called, rand acts as if srand(1) has been called.

http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#rand

Ante answered 10/1, 2013 at 5:39 Comment(0)
S
5

The C standard actually stipulates the behaviour documented in the other answers:

ISO/IEC 9899:2011 §7.22.2.2 The srand function

¶2 [...] If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.

Setiform answered 10/1, 2013 at 5:57 Comment(0)
L
2

The man pages state the following:

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

Lacedaemonian answered 10/1, 2013 at 5:39 Comment(0)
T
1
If rand() is called before any calls to srand() are made, the same sequence shall 
be generated as when srand() is first called with a seed value of 1.

Ref:

http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html

Twentyfour answered 10/1, 2013 at 6:6 Comment(0)
M
1

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

Melamine answered 10/1, 2013 at 9:2 Comment(2)
Welcome to Stack Overflow. What you say here is correct, but it very much repeats what the other, earlier answers say. I'll give you the benefit of the doubt and an upvote this time, but when a question already has a number of answers that give the same information as you'll add, you should think about whether you should add your answer. (When I added my answer, there were already two good answers; mine, however, added an authoritative reference for why the functions behave as they do — a quote from the C standard. That distinctive information was why I added an answer at all.)Setiform
Sorry, didnt realize the answer was already there. Wont repeat it from now on. Thanks for pointing out the mistake.Melamine

© 2022 - 2024 — McMap. All rights reserved.