std::srand(3)
π NAME π
std::srand - std::srand. That's the name, bestie, no notes π. This is the std::srand(3) page from the C++ Standard Libary, and it's all about seeding the random generator, so let's go π
.
πΈ Synopsis πΈ
Defined in header <cstdlib>:
void srand( unsigned seed );
Seeds the pseudo-random number generator used by std::rand() with the value seed β¨.
If std::rand() is used before any calls to srand(), std::rand() behaves as if it was seeded with srand(1). Not me learning the default seed rn π.
Each time std::rand() is seeded with the same seed, it must produce the same sequence of values. Same seed, same sequence, periodt π₯.
srand() is not guaranteed to be thread-safe. Bestie, do not assume it is, fr fr π.
π§ Parameters π§
seedβ the seed value π±
π Return value π
(none)β literally nothing comes back, bestie π
π Notes π
Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), at the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers β like, do not do that, bestie π«Ά.
Standard practice is to use the result of a call to std::time(0) as the seed. However, std::time returns a std::time_t value, and std::time_t is not guaranteed to be an integral type. In practice, though, every major implementation defines std::time_t to be an integral type, and this is also what POSIX requires. So it's giving "works in practice" energy, but the standard is not promising it π
.
π Example π
// Run this code
#include <cstdlib>
#include <ctime>
#include <iostream>
int main()
{
std::srand(std::time(0)); // use current time as seed for random generator
std::cout << "Random value on [0, " << RAND_MAX << "]: " <<
std::rand() << '\n';
}
π Possible output: π
Random value on [0, 2147483647]: 1373858591
π«Ά See also π«Ά
randβ generates a pseudo-random number (function)RAND_MAXβ maximum possible value generated bystd::rand(macro constant)reseedβ reseeds the per-thread random engine (function)- C documentation for
srandβ yep, it exists too, iykyk β¨
mwah π β source/version http://cppreference.com, dated 2024.06.10, page std::srand(3). Bye bestie, go seed responsibly πβ¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms