Should I use rand() or rand_r()?
Asked Answered
T

2

16

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?

Temikatemp answered 19/3, 2015 at 0:26 Comment(1)
If possible, use the "new" <random> facilities. rand is pretty bad. Interesting.Airflow
T
15

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.

Tiptoe answered 19/3, 2015 at 0:54 Comment(1)
It may be worthy to note that C++11's random also exists in Boost for those who can't use C++11 but can use Boost.Intersex
O
1

Use stuff from <random> of C++11.

Watch rand() considered harmful by S.T.L.

Ornithopod answered 14/11, 2015 at 21:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.