Random Number Gen C++: How to Generate Random Numbers

How-to basics · Updated November 23, 2026

In C++, the modern way to generate random numbers is to use the <random> header, which provides std::mt19937 (a Mersenne Twister engine) and distribution classes like std::uniform_int_distribution. A simple example: std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dist(1, 100); int random_number = dist(gen); This replaces the older, less reliable rand() and srand() functions from C.

Why the Old rand() Is Discouraged

For decades, C++ programmers used rand() from <cstdlib>. It’s simple: call srand(time(0)) once, then rand() returns a pseudo-random integer between 0 and RAND_MAX (often 32767). However, rand() has known problems:

  • Poor distribution: The low-order bits are notoriously non-random; using rand() % n introduces modulo bias unless n divides RAND_MAX exactly.
  • Implementation-defined quality: The algorithm varies across compilers and platforms, so your program’s behavior isn’t portable.
  • No easy way to get different distributions: You have to manually transform the integer output to get a normal, Poisson, or other distribution.

The C++11 standard introduced <random> to address these issues, and it is now the recommended approach for all new code.

Core Components of <random>

The <random> library separates two concerns: generating raw random bits (the engine) and shaping those bits into a desired distribution (the distribution).

  • Engines: Produce a sequence of unsigned integers. Common engines include std::mt19937 (Mersenne Twister, fast and good quality), std::mt19937_64 (64-bit version), std::minstd_rand (small and fast, but lower quality), and std::random_device (a non-deterministic source, if available).
  • Distributions: Transform engine output into a specific statistical distribution. Examples: std::uniform_int_distribution<int>, std::uniform_real_distribution<double>, std::normal_distribution<double>, std::bernoulli_distribution.

You always combine an engine with a distribution. The engine is seeded (initialized) with a starting value, and the distribution object is called with the engine as an argument.

Step-by-Step: Generating a Random Integer

Here’s a complete, correct example that generates a random integer between 1 and 100 (inclusive):

#include <iostream>
#include <random>

int main() {
    // Seed with a true random number from random_device
    std::random_device rd;
    // Mersenne Twister engine seeded with rd()
    std::mt19937 gen(rd());
    // Uniform distribution from 1 to 100
    std::uniform_int_distribution<int> dist(1, 100);
    // Generate and print a random number
    int random_number = dist(gen);
    std::cout << random_number << std::endl;
    return 0;
}

This code works on any C++11 or later compiler. The std::random_device is used to seed the engine with a non-deterministic value (if supported), which is better than using time(0) because it avoids predictable sequences.

How to Choose an Engine and Seed

Selecting the right engine depends on your needs:

  • General-purpose: std::mt19937 is the default choice. It’s fast, has a long period (2^19937 – 1), and passes many statistical tests.
  • Cryptographic security: None of the standard engines are cryptographically secure. For security-sensitive applications (passwords, tokens), use std::random_device directly if it’s non-deterministic, or use a dedicated library like OpenSSL’s RAND_bytes. Never use mt19937 for cryptography.
  • Reproducibility: If you need the same sequence every run (e.g., for testing), seed with a fixed constant: std::mt19937 gen(42);.
  • Seeding with random_device: std::random_device may be implemented as a pseudo-random generator on some platforms (e.g., some older MinGW versions), so it’s not guaranteed to be truly random. Still, it’s the best portable seed source.

A common pitfall is re-seeding the engine every time you need a random number. That can lead to repeated sequences if you seed with time(0) and call it quickly. Instead, create the engine once and reuse it.

Generating Different Types of Random Numbers

You can easily get other distributions:

  • Real numbers between 0 and 1: std::uniform_real_distribution<double> dist(0.0, 1.0);
  • Random boolean: std::bernoulli_distribution dist(0.5); (50% true)
  • Normal distribution: std::normal_distribution<double> dist(mean, stddev);
  • Random element from a vector: Use std::uniform_int_distribution<size_t> dist(0, vec.size() - 1); then index with vec[dist(gen)].

For a random double in a range [a, b), you can also use std::uniform_real_distribution. Note that the upper bound is exclusive for real distributions, but inclusive for integer distributions.

Common Problems and Misconceptions

Several pitfalls trip up even experienced programmers:

  • Modulo bias: Using rand() % n is biased because the range of rand() is not divisible by n. The <random> distributions handle this correctly.
  • Seeding with time(0) and calling rand() in a loop: If you call srand(time(0)) before each rand() in a fast loop, you’ll get the same number repeatedly because time doesn’t change that fast.
  • Using random_device for everything: std::random_device can be slow and may block if the system entropy pool is exhausted. Use it only for seeding.
  • Thread safety: Engines are not thread-safe. If multiple threads need random numbers, give each thread its own engine, seeded differently (e.g., with std::random_device plus a thread id).
  • Distribution objects are stateful: Some distributions (like normal) may cache values; reusing the same distribution object across threads can cause data races. Create a separate distribution per thread.

A frequent question: “Can I use rand() for a game?” Yes, if you don’t need high quality or security, but using <random> is just as easy and more reliable.

Performance and Alternatives

std::mt19937 is fast enough for most applications—generating millions of numbers per second. However, if you need even faster generation or a smaller memory footprint, consider std::minstd_rand (a linear congruential generator) or std::ranlux48 (a subtract-with-carry engine). For cryptographic randomness, use platform-specific APIs like BCryptGenRandom on Windows or /dev/urandom on Linux, or a library like OpenSSL.

Another alternative is the std::generate_canonical function, which produces a floating-point number in [0,1) from an engine, but it’s rarely needed because uniform_real_distribution does that.

Frequently Asked Questions

How do I generate a random number between 1 and 6 (like a die)?

Use std::uniform_int_distribution<int> dist(1, 6); and call dist(gen). This gives each number an equal probability, unlike rand() % 6 + 1 which is slightly biased.

What is the difference between rand() and mt19937?

rand() is a simple C function with implementation-defined quality and often poor distribution. std::mt19937 is a Mersenne Twister engine with a much longer period and better statistical properties, and it’s part of C++11’s <random> library.

Can I use time(0) to seed mt19937?

Yes, but it’s not ideal because if you seed multiple engines within the same second, they produce identical sequences. Using std::random_device is better because it provides a non-deterministic seed.

Is std::random_device truly random?

It depends on the implementation. On most modern systems (Linux, Windows, macOS), it accesses a hardware entropy source and is non-deterministic. But on some older or minimal implementations, it may be a pseudo-random generator. Always treat it as a seed source, not as a cryptographic RNG.

How do I generate a random double between 0 and 1?

Use std::uniform_real_distribution<double> dist(0.0, 1.0); and call dist(gen). This gives a value in [0,1) with uniform probability.

Can I use random numbers in multithreaded programs?

Yes, but each thread should have its own engine and distribution objects to avoid data races. Seed each engine differently, for example by combining std::random_device with a thread-specific value like std::hash<std::thread::id>.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.