rand() Generate a pseudo-random integer

rand() Generate a pseudo-random integer

rand() returns a pseudo-random integer from 0 through RAND_MAX. Sequences are implementation-specific; avoid modulo bias and never use it for security.

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

📝 Syntax

int rand(void);

Returns: Returns a pseudo-random integer between 0 and RAND_MAX, inclusive.

▶ Example

Edit the C code below and click Run; the server compiles and executes it:

Output:

<three implementation-dependent integers from 0 to RAND_MAX, one per line>
RAND_MAX = <implementation-defined, at least 32767>
⚠️ Warning The sequence and RAND_MAX are implementation-dependent. Even with srand(1), do not expect identical values across platforms; the output shows only the form.
💡 Tip rand() is unsuitable for cryptography or security tokens. Simple modulo reduction can also introduce bias; use a more rigorous method when uniformity matters.

📚 Related Tutorials

❓ FAQ

QWhy does rand produce the same sequence on every run?
AWithout an srand call, rand behaves as though seeded with 1, so the same implementation repeats its sequence. A varying seed produces different sequences.
QHow can I generate an integer in a requested range with rand?
AScale the result using RAND_MAX for the desired interval, while accounting for modulo bias and range width. Do not assume RAND_MAX is 32767; use the macro itself.
QWhy is rand() % n not guaranteed to be perfectly uniform?
AWhen n does not divide RAND_MAX+1 evenly, different remainders correspond to different numbers of raw results, so simple modulo reduction introduces bias; some implementations may also have poor-quality low bits. When uniformity matters, use rejection sampling to discard the leftover values that cannot be grouped evenly, and choose a random source of known quality.
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%

🙏 帮我们做得更好

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

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