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.
| Category | stdlib.h utilities |
|---|---|
| Kind | Library function |
| Header | <stdlib.h> |
| C standard | C89 / 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 stdlib.h functions
📚 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.