In C, the standard way to generate random numbers is the rand() function from <stdlib.h>, which returns a pseudo-random integer between 0 and RAND_MAX (typically 32767). To get numbers in a specific range, you use the modulo operator, and to avoid the same sequence on every run, you seed it with srand() using a changing value like the current time.
How rand() Works Under the Hood
rand() is a pseudo-random number generator (PRNG). It produces a deterministic sequence based on an internal state. The C standard does not specify the algorithm; implementations commonly use a linear congruential generator (LCG) of the form:
state = (state * a + c) % m
where a, c, and m are constants. The output is derived from the state. Because the sequence is deterministic, calling rand() without seeding gives the same sequence every run—useful for debugging but not for games or security.
Seeding with srand()
To get different sequences, call srand() once at the start of your program, typically with the current time:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
printf("%d\n", rand());
return 0;
}
time(NULL) returns the current calendar time in seconds, which changes each second. If you run the program twice within the same second, you get the same sequence. For finer granularity, use a higher-resolution clock like clock_gettime() on POSIX systems.
Generating Numbers in a Range
The common pattern is rand() % N to get a number from 0 to N-1. For example, to simulate a die roll (1 to 6):
int roll = (rand() % 6) + 1;
However, this has a flaw: if RAND_MAX is not evenly divisible by N, the lower values are slightly more likely. For non-critical uses, it’s acceptable. For a more uniform distribution, use rejection sampling:
int get_random(int min, int max) {
int range = max - min + 1;
int limit = RAND_MAX - (RAND_MAX % range);
int r;
do {
r = rand();
} while (r >= limit);
return min + (r % range);
}
Common Pitfalls and Misconceptions
One common mistake is calling srand() inside a loop, which resets the sequence each iteration and often yields the same number repeatedly. Seed once at program start.
Another misconception is that rand() is cryptographically secure. It is not—it’s predictable. For passwords, tokens, or any security-sensitive use, use a proper cryptographic RNG like getrandom() on Linux or arc4random() on BSD/macOS.
Also, rand() is not thread-safe. In multithreaded programs, use rand_r() (with a per-thread seed) or a thread-safe library.
Alternatives to rand()
For better quality or control, consider these:
random()andsrandom()—POSIX, better statistical properties thanrand().drand48()family—POSIX, returns double in [0,1).- C++
<random>—if you can use C++, provides many engines (e.g.,mt19937) with better distribution and control. - For cryptographic use:
getrandom(),arc4random(), orRAND_bytesfrom OpenSSL.
Performance and Thread Safety
rand() is fast—microseconds per call. However, it uses a global state, so concurrent calls can race. Use rand_r() with a local seed variable:
unsigned int seed = time(NULL);
int r = rand_r(&seed);
For high-performance parallel generation, consider using a separate PRNG per thread, like drand48_r() on glibc systems.
Frequently Asked Questions
Why does rand() return the same number every time I run my program?
Because you haven’t called srand(). Without seeding, the generator starts with the same internal state each run, so it produces the same sequence. Add srand(time(NULL)) at the start of main().
How do I get a random number between 1 and 100?
Use (rand() % 100) + 1. The modulo gives 0-99, adding 1 shifts to 1-100. For better uniformity, use the rejection method described above.
Is rand() safe for generating passwords?
No. rand() is predictable; an attacker who knows the seed or observes a few outputs can predict the rest. Use a cryptographic RNG like getrandom() or arc4random().
Can I use rand() in multithreaded programs?
Not safely without locking. Use rand_r() with a per-thread seed, or use a thread-local PRNG. Alternatively, use C++ <random> with a separate engine per thread.
What is RAND_MAX?
It’s a constant defined in <stdlib.h> that gives the maximum value returned by rand(). On most systems it’s 32767, but it can be larger (e.g., 2147483647 on some 32-bit systems). Check your compiler’s documentation.
How do I generate a random floating-point number between 0 and 1?
Cast rand() to double and divide by RAND_MAX: double r = (double)rand() / RAND_MAX;. This gives a value in [0,1]. For a more uniform distribution, use drand48() if available.