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 ofrand(...)
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?
The rand() function shall return the next pseudo-random number in the sequence. The rand_r() function shall return a pseudo-random integer. The srand() function shall not return a value.
rand() is not threadsafe, but rand_r() is. The rand() function generates a pseudo-random integer in the range 0 to RAND_MAX (macro defined in <stdlib. h>). Use the srand() function before calling rand() to set a starting point for the random number generator.
The rand_r() function generates a sequence of pseudo-random integers in the range 0 to RAND_MAX. (The value of the RAND_MAX macro will be at least 32767.)
rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With