srand() Seed the pseudo-random number generator
srand() Seed the pseudo-random number generator
srand() seeds rand(); identical seeds reproduce sequences only within one implementation. Seed once, not in a loop; it adds no cryptographic security.
| Category | stdlib.h utilities |
|---|---|
| Kind | Library function |
| Header | <stdlib.h> |
| C standard | C89 / C90 |
📝 Syntax
void srand(unsigned int seed);
⚙️ Parameters
| seed Required | An unsigned integer seed used to initialize the pseudo-random sequence. |
|---|
Returns: No value is returned.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Same seed, same first value: yes
⚠️ Warning The same seed reproduces a sequence within one implementation, but not necessarily across implementations. The example compares only the two generated values.
💡 Tip A program normally seeds once at startup and then calls rand() repeatedly. Seeding inside a loop continually resets the sequence.
🏷️ Related stdlib.h functions
📚 Related Tutorials
❓ FAQ
QShould srand be called inside a loop?
AUsually not. Each call resets the sequence, and an unchanged seed can make every iteration return the same value. Seed once during program initialization.
QIs seeding srand with the current time secure?
AIt adds variability for ordinary simulations or games but provides no cryptographic security. A time seed can be guessed; security-sensitive uses require a dedicated secure random source.
QWhy can different compilers produce different sequences from the same srand seed?
AThe standard guarantees reproducibility for the same seed only within one implementation; it does not mandate the generation algorithm, internal state, or RAND_MAX. Different compilers, runtime libraries, and platforms may use different algorithms, so tests should not hard-code random output across platforms, and security uses must not rely on this mechanism.