To generate a random integer in modern C++, use the <random> header with a random engine and a distribution, for example std::mt19937 and std::uniform_int_distribution. The old C-style rand() function still works but has known quality issues, so the <random> library is the recommended approach for new code.
Why rand() Is Outdated
For decades, C++ programmers used rand() from <cstdlib>. It returns a pseudo-random integer between 0 and RAND_MAX (often 32767). The problems are:
- Poor distribution quality: The underlying algorithm is implementation-defined and often uses a simple linear congruential generator, which can show patterns.
- Limited range:
RAND_MAXis often small, making it hard to get large random numbers without extra work. - Modulo bias: Using
rand() % nto get a range introduces bias unlessndividesRAND_MAX+1exactly. - Global state:
srand()sets a global seed, which can interfere with other parts of a program.
Because of these issues, the C++ standard library introduced <random> in C++11, offering better engines and distributions.
The Modern Approach: <random> and Distributions
The <random> header provides several random number engines and distribution classes. The most common engine is std::mt19937 (Mersenne Twister), which is fast and has good statistical properties. To generate an integer in a specific range, use std::uniform_int_distribution.
Here is a complete example that prints 10 random integers between 1 and 100:
#include <iostream>
#include <random>
int main() {
std::random_device rd; // Obtain a seed from hardware if available
std::mt19937 gen(rd()); // Seed the Mersenne Twister engine
std::uniform_int_distribution<int> dist(1, 100);
for (int i = 0; i < 10; ++i) {
std::cout << dist(gen) << ' ';
}
std::cout << '\n';
return 0;
}
This code creates a std::random_device to get a non-deterministic seed, uses it to seed a Mersenne Twister engine, and then creates a uniform distribution for the range [1, 100]. Each call to dist(gen) returns a new random integer.
How to Choose an Engine and Seed
The C++ standard defines several engines, each with different trade-offs:
std::mt19937– Mersenne Twister, good balance of speed and quality, period of 219937-1.std::mt19937_64– 64-bit version, produces larger integers.std::minstd_rand– minimal standard linear congruential, fast but lower quality.std::ranlux48– subtract-with-carry, higher quality but slower.
For seeding, std::random_device is the recommended way to get a non-deterministic seed. However, some implementations (like MinGW on Windows) may not provide true hardware randomness and could return the same sequence each run. In such cases, you can combine it with the current time:
std::mt19937 gen(std::random_device{}() ^
static_cast<unsigned>(std::time(nullptr)));
But be aware that time-based seeds are predictable; for security-sensitive applications, use a cryptographically secure generator (see below).
Common Pitfalls and How to Avoid Them
- Re-seeding every call: Creating a new engine and seeding it inside a loop can produce the same numbers repeatedly if the seed is time-based. Create the engine once and reuse it.
- Modulo bias with
rand(): If you must userand(), avoid% nfor ranges that are not divisors ofRAND_MAX+1. Instead, use a rejection method orstd::uniform_int_distributionwithrand()as the engine. - Using
std::random_deviceas the engine:std::random_deviceis not meant to be used directly for generating many numbers; it is slow and may block. Use it only to seed a proper engine. - Ignoring thread safety: The standard engines are not thread-safe. If multiple threads generate random numbers, give each thread its own engine or use a mutex.
Generating Random Integers in a Range: The Right Way
To generate an integer uniformly in [a, b], use std::uniform_int_distribution<int> dist(a, b);. This distribution handles the bias problem internally. For a non-uniform distribution, you can use other distributions like std::binomial_distribution or std::poisson_distribution.
If you need a random boolean, you can use std::uniform_int_distribution<int> dist(0, 1) or std::bernoulli_distribution.
Cryptographically Secure Random Integers
For security-sensitive applications (e.g., generating tokens, keys), the standard <random> engines are not suitable because they are predictable once the seed is known. In C++ you can use:
std::random_devicedirectly, if it is implemented to be non-deterministic (check your implementation).- Platform-specific APIs:
RAND_byteson OpenSSL,BCryptGenRandomon Windows,getrandomon Linux. - C++23’s
std::random_devicemay be improved, but as of C++20 it is not guaranteed to be secure.
Always consult your platform’s documentation for secure random generation.
Performance and Memory Considerations
Generating a random integer with <random> is fast, but the Mersenne Twister engine has a large internal state (about 2.5 KB). If memory is a concern, use a smaller engine like std::minstd_rand. If you need many random numbers, reuse the engine and distribution objects instead of recreating them.
For extremely high-performance needs, consider using a fast generator like std::mt19937_64 or a third-party library such as PCG, but the standard library is sufficient for most applications.
Frequently Asked Questions
Q: Can I use rand() in modern C++?
Yes, it still works, but it is not recommended for new code due to quality and bias issues. The <random> library is the standard way.
Q: How do I generate a random integer between 0 and 9?
Use std::uniform_int_distribution<int> dist(0, 9); and call dist(gen).
Q: Why do I get the same sequence every time I run my program?
If you seed with a constant or with std::random_device that is not truly random, the sequence repeats. Use a different seed each run, e.g., std::random_device{}().
Q: Is std::random_device secure?
Not necessarily. It may be implemented as a pseudo-random generator on some platforms. For security, use platform-specific secure APIs.
Q: How do I generate a random integer in a range without bias?
Use std::uniform_int_distribution; it internally avoids modulo bias.
Q: Can I use std::mt19937 in a multi-threaded program?
Each thread should have its own engine instance to avoid data races.
Related
- Computer Generated Random Numbers Explained
- Overview of Balance Sheet: Key Parts Explained
- Balance of Budget Statement Example
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- KPI Spreadsheet Setup: Step-by-Step GuideSetting up a KPI (Key Performance Indicator) spreadsheet gives you a single, organized place to track the numbers…
- Remove Page Break Lines in Excel: Steps for Every SheetTo hide page break lines in Excel for Microsoft 365 on Windows, open File > Options > Advanced,…
- Excel Unmerge Cells Shortcut: Keys, Steps, and FixesIn Excel for Microsoft 365 on Windows, select a merged cell and press Alt, H, M, U—one key…
- PowerPoint Timeline: The Easiest Way to Make One QuicklyThe easiest way to make a timeline in PowerPoint is to use SmartArt: go to Insert > SmartArt…
- WORKDAY.INTL in Google Sheets: Syntax & ExamplesThe WORKDAY.INTL function in Google Sheets calculates the date that falls a specified number of working days before…
- Google Sheets Query Multiple Criteria: How-ToTo query multiple criteria in Google Sheets, use the QUERY function with a WHERE clause that combines conditions…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.