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.

Categorystdlib.h utilities
KindLibrary function
Header<stdlib.h>
C standardC89 / C90

📝 Syntax

void srand(unsigned int seed);

⚙️ Parameters

seed RequiredAn 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏