How to generate a random int in C?
c, random
Solution
Note: Don't use `rand()` for security. If you need a cryptographically secure number, see this answer instead.
#include <time.h>
#include <stdlib.h>
srand(time(NULL)); // Initialization, should only be called once.
int r = rand(); // Returns a pseudo-random integer between 0 and RAND_MAX.
On Linux, you might prefer to use random and srandom.
Problem
Is there a function to generate a random int number in C? Or will I have to use a third party library?
Related problems
- srand() — why call it only once?
- How to generate random float number in C
- Generate a random number within range?
- Generate random numbers uniformly over an entire range
- How do I get a specific range of numbers from rand()?
- How to get the current time in milliseconds from C in Linux?
- RDRAND and RDSEED intrinsics on various compilers?