To generate a random number within a specific range in C++, use the std::uniform_int_distribution class from the <random> header, combined with a random engine like std::mt19937. For example, to get a random integer between 1 and 100 inclusive: std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dist(1, 100); int random = dist(gen);.
Why the Old rand() and srand() Are Obsolete
Many older tutorials show rand() % range + min, but this approach has serious flaws. The rand() function uses a linear congruential generator (LCG) that produces numbers with poor statistical distribution, and using modulo introduces bias unless the range evenly divides the generator’s period. Additionally, rand() is not thread-safe and its quality varies across implementations. The C++11 standard introduced the <random> library to address these issues, offering better randomness, more control, and predictable behavior. If you are writing new code, always prefer <random> over rand().
How the <random> Library Works
The <random> library separates the generation of raw random bits from the distribution of those bits into a range. A random engine (like std::mt19937, a Mersenne Twister) produces a sequence of unsigned integers. A distribution (like std::uniform_int_distribution) takes those raw values and maps them to a specified range with uniform probability. This separation lets you choose the engine based on speed, memory, or randomness quality, and the distribution ensures unbiased results.
Here is a minimal working example:
#include <iostream>
#include <random>
int main() {
std::random_device rd; // Obtain a random seed from hardware
std::mt19937 gen(rd()); // Seed the Mersenne Twister engine
std::uniform_int_distribution<int> dist(1, 100);
int random_number = dist(gen);
std::cout << "Random number: " << random_number << std::endl;
return 0;
}
In this code, std::random_device provides a non-deterministic seed (often from the operating system), which is used to initialize the engine. Then dist(gen) returns a single random integer in the inclusive range [1, 100].
Choosing the Right Distribution and Engine
For integer ranges, use std::uniform_int_distribution<int> (or <long long> for larger ranges). For floating-point numbers, use std::uniform_real_distribution<double>, which generates a value in the half-open interval [a, b) — note that b is not included. For example, to get a random double between 0.0 and 1.0:
std::uniform_real_distribution<double> dist(0.0, 1.0);
double r = dist(gen);
When selecting an engine, std::mt19937 is a good default because it offers a good balance of speed and quality. For cryptographic purposes, you should use std::random_device directly, but note that it may be slower and its output is not guaranteed to be non-deterministic on all implementations. For simulations requiring high repeatability, you can use a fixed seed (e.g., std::mt19937 gen(42);) to reproduce the same sequence every run.
Common Pitfalls and How to Avoid Them
- Re-seeding every call: Creating a new engine and seeding it each time you need a random number is slow and can produce repetitive sequences if the seed is the same (e.g., if you use
time(NULL)and call rapidly). Instead, create the engine once and reuse it. - Using
rand() % nfor small ranges: As mentioned, this introduces bias. Usestd::uniform_int_distribution. - Ignoring the inclusive/exclusive nature of ranges: For integers, the distribution is inclusive of both endpoints. For floating-point, the upper bound is exclusive. This often surprises beginners.
- Thread safety: The standard engines are not thread-safe. If you need random numbers from multiple threads, give each thread its own engine (seeded differently) or use a mutex to protect a shared engine.
- Forgetting to include
<random>: This seems obvious, but it’s a common compile error.
Generating a Random Number in a Range Without Bias
If you must use rand() for legacy code, you can reduce bias by using rejection sampling. Here is a correct way to get a uniform integer in [min, max]:
int rand_range(int min, int max) {
int range = max - min + 1;
int max_valid = RAND_MAX - (RAND_MAX % range);
int r;
do {
r = rand();
} while (r >= max_valid);
return min + (r % range);
}
This discards values that would cause modulo bias. However, this is still limited by the quality of rand() itself. For new code, use the <random> library.
Real-World Example: Simulating a Dice Roll
Suppose you want to simulate rolling a six-sided die. The code is nearly identical to the earlier example:
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> die(1, 6);
for (int i = 0; i < 10; ++i) {
std::cout << die(gen) << " ";
}
std::cout << std::endl;
return 0;
}
This will print 10 random numbers from 1 to 6. The distribution ensures each face has an equal chance of appearing, which is what you want for a fair die.
Performance and Memory Considerations
Creating a std::mt19937 engine is relatively cheap, but it does maintain a state of 2.5 kilobytes. If you need many random numbers in a tight loop, create the engine once and reuse it. The generation itself is fast—millions of numbers per second. If you need extreme speed and are okay with lower quality, you might use a simpler engine like std::minstd_rand (a linear congruential engine) or std::ranlux48 for better distribution at a cost of speed. For most applications, std::mt19937 is the recommended default.
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 then call dist(gen). This gives a double in the half-open interval [0, 1), meaning 0 is possible but 1 is not. If you need 1 included, use std::uniform_real_distribution<double> dist(0.0, std::nextafter(1.0, 2.0)); to include 1.0, but that is rarely necessary.
Can I use std::random_device directly for random numbers?
Yes, std::random_device can be called directly: int r = rd(); but it returns an unsigned integer in the range of the device, which may not be uniform in the way you expect. It is intended for seeding engines, not for generating a sequence of random numbers directly, because it might be slow and its output quality is not guaranteed to be uniform across implementations.
Why does my random number sequence repeat when I run the program twice?
If you use a fixed seed (e.g., std::mt19937 gen(42);), the sequence will be identical each run. This is useful for debugging. To get different sequences each run, seed with std::random_device or with the current time (e.g., std::chrono::system_clock::now().time_since_epoch().count()). However, using time is not recommended for security-sensitive applications.
What is the difference between std::uniform_int_distribution and std::uniform_real_distribution?
The integer distribution generates integers and includes both endpoints. The real distribution generates floating-point values and excludes the upper endpoint by default. Also, the integer distribution is exact and unbiased, while the real distribution may have slight rounding issues due to floating-point representation, but these are negligible for most uses.
Is it safe to use rand() with srand(time(NULL)) for a simple game?
For a simple game where security and statistical perfection are not critical, rand() is acceptable, but you should be aware of its limitations. The main issues are that rand() can be predictable and biased. If you are just rolling dice for a board game, it’s fine. If you are distributing prizes or generating passwords, use <random> instead.
Related
- Cut Shortcut PC: What It Does & How to Use It
- Split in Java String: Methods, Examples, and Pitfalls
- Number 5 Blue Balloon Meaning & Origins
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Monthly Budget Tracker Template for Google Sheets?A monthly budget tracker template for Google Sheets can be built from a transaction log, a monthly category…
- Excel Conditional Formatting 4-Color Scale ExplainedExcel for Microsoft 365 does not have a built-in four-color scale: its Color Scales feature offers two- and…
- Excel Flash Fill: How It Works and When to Use ItExcel Flash Fill recognizes a pattern in examples you enter and fills the rest of a column with…
- Conditional Format Highlight Row: Full GuideYes, you can highlight an entire row with conditional formatting in Excel by basing the rule on a…
- How to Make a Color Key in Excel for Clearer SheetsTo make a color key in Excel, set aside a small area of the worksheet, add a labeled…
- Capitalize First Letter in Excel QuicklyThe quickest way to capitalize only the first character in an Excel cell is to use a formula…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.