Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/numeric/random/rand"

From cppreference.com
< cpp‎ | numeric‎ | random
m (Shorten template names. Use {{lc}} where appropriate.)
m (Update links.)
Line 47: Line 47:
 
===See also===
 
===See also===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/numeric/random/dcl list srand}}
+
{{dsc inc | cpp/numeric/random/dsc srand}}
 
{{dsc see c | c/numeric/random/rand}}
 
{{dsc see c | c/numeric/random/rand}}
 
{{dsc end}}
 
{{dsc end}}

Revision as of 22:20, 31 May 2013

 
 
 
 
Defined in header <cstdlib>
int rand();

Returns a pseudo-random integral value between 0 and RAND_MAX (0 and RAND_MAX included).

srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1).

Each time rand() is seeded with srand(), it must produce the same sequence of values on successive calls. Other functions in the standard library may call rand, it is implementation-defined which functions do so.

It is implementation-defined whether rand() is thread-safe.

Contents

Parameters

(none)

Return value

Pseudo-random integral value between 0 and RAND_MAX.

Notes

There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls).

rand() is not recommended for serious random-number generation needs, like cryptography.

Example

#include <cstdlib>
#include <iostream>
#include <ctime>
 
int main() 
{
    std::srand(std::time(0)); // use current time as seed for random generator
    int random_variable = std::rand();
    std::cout << "Random value on [0 " << RAND_MAX << "]: " 
              << random_variable << '\n';
}

Possible output:

Random value on [0 2147483647]: 1373858591

See also

seeds pseudo-random number generator
(function) [edit]