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?

tkruse
  • 10,222
  • 7
  • 53
  • 80
Barbara Krein
  • 329
  • 2
  • 7
  • 6
    If possible, use the "new" `` facilities. `rand` is pretty bad. [Interesting](http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful). – Baum mit Augen Mar 19 '15 at 00:31

2 Answers2

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.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • 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. – Morwenn Mar 19 '15 at 08:01
1

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

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

vladon
  • 8,158
  • 2
  • 47
  • 91