calling srand on the lines of srand(time(NULL));
is required to setup the seed for rand()
to generate a random number.
My question is what is the need for the seed ?

- 1,880
- 3
- 20
- 35
-
1***My question is what is the need for the seed ?*** If you do not seed or seed with a fixed value you will get the same set of random numbers each time you run your application. – drescherjm Feb 04 '15 at 20:41
-
4I feel the need... the need... **for seed!** [*](http://en.wikiquote.org/wiki/Top_Gun) – Mark Ransom Feb 04 '15 at 20:44
-
@MarkRansom and _I feel the need... the need... for s(p)eed !!_ – Sourav Ghosh Feb 04 '15 at 20:46
-
Do you know [**what** a seed is](http://stackoverflow.com/questions/22915400)? I suspect that if you knew *what*, you would know *the need*. – Drew Dormann Feb 04 '15 at 20:48
4 Answers
The rand()
function is a pseudo-random number generator, i.e.,
The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive
The generation of the pseudo-random number depends on the seed. If you don't provide a different value as seed, you'll get the same random number on every invocation(s) of your application. That's why, the srand()
is used to randomize the seed itself.
Most common practice : srand(time(NULL))
[Suitable for single-run evaluations].
what is the need for the [explicit] seed ?
Worthy to mention, from the man page
If no seed value is provided, the rand() function is automatically seeded with a value of 1.

- 133,132
- 16
- 183
- 261
I guess your question is why isn't it seeded automatically with an unpredictable value (like the current time).
Having the random number generator generate the same sequence every time a program starts can be handy for debugging.

- 62,093
- 7
- 131
- 191

- 28,327
- 8
- 59
- 66
-
Sir, please correct me if i'm wrong, but isn't it like it __is__ actually seeded automatically with a value `1` [without an explicit seed]. – Sourav Ghosh Feb 04 '15 at 20:48
-
1Yes indeed - it is seeded with a known constant (1). – 500 - Internal Server Error Feb 04 '15 at 20:58
Random number generation is the result of an iterative process. Each time you call rand the following happens:
seed := create_new_seed(seed);
return random_number_from_seed(seed);
(Note that create_new_seed
and random_number_from_seed
are pure functions, they only use their parameters and do not access any globals).
This means that if the seed is always 0, then the series of values returned by rand
calls will always be the same. In order to allow for different values, a different seed is used in each run. One thing that changes between runs and can easily be used is the start time of the program.

- 5,344
- 1
- 25
- 47
If you do not add srand(), each time you run your program, rand will generate the same random numbers.

- 6,421
- 4
- 29
- 43