Random Integer in C++: How to Generate It

How-to basics · Updated November 23, 2026

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_MAX is often small, making it hard to get large random numbers without extra work.
  • Modulo bias: Using rand() % n to get a range introduces bias unless n divides RAND_MAX+1 exactly.
  • 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 use rand(), avoid % n for ranges that are not divisors of RAND_MAX+1. Instead, use a rejection method or std::uniform_int_distribution with rand() as the engine.
  • Using std::random_device as the engine: std::random_device is 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_device directly, if it is implemented to be non-deterministic (check your implementation).
  • Platform-specific APIs: RAND_bytes on OpenSSL, BCryptGenRandom on Windows, getrandom on Linux.
  • C++23’s std::random_device may 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

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.