rand - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# rand

From cppreference.com
< c‎ | numeric‎ | random

Defined in header `<stdlib.h>` |  |
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.

`rand()` is not guaranteed to be thread-safe.

### [edit] Parameters

(none)

### [edit] Return value

Pseudo-random integral value between ​0​ and RAND_MAX.

### [edit] 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.

### [edit] Example

Run this code

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>

    int main(void)
    {
        srand(time(0)); //use current time as seed for random generator
        int random_variable = rand();
        printf("Random value on [0,%d]: %d\n", RAND_MAX, random_variable);
    }

Possible output:

    Random value on [0 2147483647]: 1373858591

### [edit] See also

srand | seeds pseudo-random number generator (function) [edit]
RAND_MAX | maximum possible value generated by rand() (macro constant) [edit]
C++ documentation for rand

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=c/numeric/random/rand&oldid=71059"