Should I use rand() or rand_r()?
Both, sort of.
The rand()
function is defined by the C standard, and has been since the first such standard in 1989/1990; it's included by reference in the C++ standard. Since rand()
depends on state, it is not thread-safe.
The rand_r()
function was designed as a thread-safe alternative to rand()
. It is not defined by the ISO C or C++ standard. It was defined by POSIX.1-2001, but marked as obsolete by POSIX.1-2008 (meaning that it's still defined by the POSIX standard, but it may be removed in a future version).
Implementations of rand()
, and therefore of rand_r()
, can be low quality. There are much better pseudo-random number generators. For C++, the <random>
library was added in C++11, and provides a number of different options.
If you want maximum portability and you don't care too much about the quality or predictability of the generated numbers and thread-safety is not a concern, you can use srand()
and rand()
. Otherwise, if you have a C++11 implementation available, use the features defined in the <random>
header. Otherwise, consult your system's documentation for other pseudo-random number generators.
References: POSIX, <random>
on cppreference.com.
Use stuff from <random>
of C++11.
Watch rand() considered harmful by S.T.L.