The simplest way to generate a random integer in a specific range in modern C++ is to use the <random> header with a std::uniform_int_distribution and a random engine like std::mt19937. For example, to get a random number between 1 and 100 inclusive, you write: std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dist(1, 100); int value = dist(gen);
Why the Old rand() Approach Is Problematic
Before C++11, the standard way was rand() % range + min. This still appears in many tutorials, but it has two real flaws. First, rand() typically has a period of only 2^31 and often produces patterns in the low bits, so % can bias results—especially when the range does not evenly divide the maximum value. Second, rand() is not thread-safe and uses a global state, which makes concurrent code unpredictable. The <random> library fixes all of these by giving you separate, controllable engines and unbiased distributions.
How std::uniform_int_distribution Works
The distribution takes two parameters: the inclusive lower bound and the inclusive upper bound. It guarantees that every integer in that closed interval has an equal probability of being produced, regardless of the engine’s internal range. The engine (e.g., std::mt19937) generates raw bits, and the distribution maps those bits to your range without modulo bias. This is a key difference from the old % method: the distribution internally discards or rejects values that would cause bias, so the output is mathematically uniform.
For floating-point numbers, use std::uniform_real_distribution<double> with a half-open range [a, b). For example, std::uniform_real_distribution<> dist(0.0, 1.0) gives a random double between 0.0 (inclusive) and 1.0 (exclusive).
Step-by-Step: Generate a Random Integer in a Range
- Include the header:
#include <random>. - Create a random device:
std::random_device rd;—this seeds the engine with a hardware-based entropy source where available. - Create an engine and seed it:
std::mt19937 gen(rd());—Mersenne Twister is a good default for most applications. - Define the distribution with your range:
std::uniform_int_distribution<> dist(1, 100);. - Call the distribution with the engine:
int random_number = dist(gen);.
Each call to dist(gen) produces a new random value. You can reuse the same engine and distribution for multiple calls; do not recreate them each time, as that wastes entropy and may produce correlated values.
Choosing the Right Engine and Seeding
The <random> header offers several engines. std::mt19937 is a solid all-purpose choice—it has a long period and is fast. For non-cryptographic simulations, it is fine. If you need better statistical quality for Monte Carlo work, consider std::mt19937_64 (64-bit version). For very small programs or when memory is tight, std::minstd_rand is a lighter linear congruential engine, but it has a shorter period.
Seeding matters. Using std::random_device is standard, but on some platforms it may be deterministic or slow. A common alternative is to seed with the current time: std::mt19937 gen(static_cast<unsigned>(std::time(nullptr))), but that is predictable if someone knows the time. For security-sensitive contexts (like generating tokens), use a cryptographic RNG instead—C++ does not have one in the standard library, so you would need a library like OpenSSL or the OS-specific API.
Common Mistakes and How to Avoid Them
- Re-seeding every call: Creating a new engine and seeding it with
random_deviceeach time you need a number is wasteful and can produce repeated values if the seed is the same. Create the engine once and reuse it. - Using
%withrand(): As explained, this introduces modulo bias. Even if the range is small, the low bits ofrand()are often not uniform. Always useuniform_int_distribution. - Off-by-one errors: Remember that
uniform_int_distributionis inclusive on both ends. If you want numbers from 0 to 9, writedist(0, 9), notdist(0, 10). - Forgetting to include
<random>: Some compilers may implicitly include it via other headers, but it is not guaranteed. Always include it explicitly. - Using
std::random_devicefor large-scale generation:random_deviceis meant for seeding, not for generating many numbers. It can be slow or block. Use it only to seed the engine.
Comparing C++11 <random> with Other Languages
If you come from Python, you might be used to random.randint(1, 100). C++ requires more setup because it separates the engine (the source of randomness) from the distribution (the shape of the output). This separation is actually a strength: it lets you swap engines without changing your code. In Java, ThreadLocalRandom.current().nextInt(1, 101) is similar to C++’s distribution but uses a built-in engine. C++ gives you explicit control over seeding, which is crucial for reproducible simulations—you can save the seed and replay the same sequence.
Performance and Thread Safety
Engines like std::mt19937 are not thread-safe. If multiple threads generate random numbers, each thread should have its own engine, seeded differently (e.g., using a thread-local seed). Alternatively, use a mutex to serialize access, but that hurts performance. For high-throughput parallel code, consider using a separate engine per thread with seeds derived from a master seed. The distribution itself is lightweight and does not hold state, so it can be shared.
Performance-wise, uniform_int_distribution is fast—typically a few nanoseconds per call. The main cost is the engine’s state update. std::mt19937 is slower than a simple LCG but still acceptable for most uses. If you need extreme speed and can tolerate lower quality, std::minstd_rand is a good choice.
Frequently Asked Questions
How do I generate a random number between 0 and 1 in C++?
Use std::uniform_real_distribution<double> dist(0.0, 1.0); and call dist(gen). This gives a double in [0, 1) with uniform probability. For a float, use std::uniform_real_distribution<float>.
Can I use std::rand() safely if I only need a small range?
Technically you can, but the bias is still present. For example, if RAND_MAX is 32767 and you want numbers 0–9, the values 0–7 appear slightly more often than 8–9 because 32768 is not divisible by 10. For most casual uses the bias is negligible, but for any serious statistical work or games, use <random>.
How do I generate a random number in a range without repeating the same number twice?
The standard distribution does not prevent repeats—it is independent. To avoid immediate repeats, you can keep the last value and regenerate if it matches, but that changes the distribution slightly. For a true non-repeating sequence, you could shuffle a vector of all possible values and iterate through it.
Is std::mt19937 cryptographically secure?
No. It is a pseudo-random number generator (PRNG) and is not designed for security. If you need unpredictable numbers for passwords or tokens, use a cryptographic RNG from the operating system (e.g., std::random_device on some platforms, or OpenSSL’s RAND_bytes).
What is the difference between std::uniform_int_distribution and std::uniform_real_distribution?
The integer version returns integers in a closed interval [a, b] (both ends included). The real version returns floating-point numbers in a half-open interval [a, b) (the lower bound is included, the upper is not). This matches the typical mathematical convention for real numbers and avoids issues with representing the upper bound exactly.
Can I generate a random number in a range using C++17 or C++20 features?
Yes, the <random> library is available since C++11 and has not changed much. C++17 and C++20 added other features like std::sample and std::shuffle that use the same distribution. No new random number generation syntax was added, so the code above works in all modern C++ versions.
Related
- Balance Sheet Equity Accounts Explained Clearly
- Google Sheets Split by Line Break: How-To
- Data Entry Jobs This Week: Where to Find Them
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets vs Microsoft Excel: Which Should You Use?Google Sheets and Microsoft Excel are spreadsheet programs for organizing data, calculating results, and making charts. Sheets is…
- Why Excel Files Get Corrupted and How to Prevent ItAn Excel file usually gets corrupted when its data cannot be written or read correctly—for example, after a…
- Online Budget Spreadsheet Free? Options, Costs and SetupYes. You can make a budget online for free with Google Sheets or Excel for the web, or…
- Can You Create Your Own Outlook Email Distribution List?Yes. You can create a personal list of recipients in Outlook and use it to address one email…
- Excel Power Query Window White Box: Causes and FixesIf the Excel Power Query window opens as a blank white box, first wait briefly, then close and…
- Online Casio Graphing Calculator: How to Use ItYes, you can use a Casio graphing calculator online for free through official emulator software and reputable web-based…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.