Search code examples
c++cppcheckcpplint

Should I use rand() or rand_r()?


I'm trying to get a random number in C++ and I'm using rand(). This is what cpplint says:

Consider using rand_r(...) instead of rand(...) for improved thread safety.

I'm switching to rand_r and this is what cppcheck says:

Obsolete function 'rand_r' called. It is recommended to use the function 'rand' instead.

Who is right?


Solution

  • 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.