...
Code Block | ||
---|---|---|
| ||
int i=0; for (i=0; i<10; i++) { printf("%d, ", rand()); /* Always generates the same sequence */ } output: 1st run: 41, 18467, 6334, 26500, 19169, 15724, 11478, 29358, 26962, 24464, 2nd run: 41, 18467, 6334, 26500, 19169, 15724, 11478, 29358, 26962, 24464, ... nth run: 41, 18467, 6334, 26500, 19169, 15724, 11478, 29358, 26962, 24464, |
...
Noncompliant Code Example
Use srand()
before rand()
to seed the random sequence generated by rand()
. The code produces different random number sequences at different calls.
Code Block | ||
---|---|---|
| ||
srand(time(NULL)); /* Create seed based on current time */ int i=0; for (i=0; i<10; i++) { printf("%d, ", rand()); /* Generates different sequences at different runs */ } output: 1st run: 25121, 15571, 29839, 2454, 6844, 10186, 27534, 6693, 12456, 5756, 2nd run: 25134, 25796, 2992, 403, 15334, 25893, 7216, 27752, 12966, 13931, 3rd run: 25503, 27950, 22795, 32582, 1233, 10862, 31243, 24650, 11000, 7328, ... |
Although the rand()
function is now properly seeded, this solution is still noncompliant because the numbers generated by rand() have a comparatively short cycle, and the numbers may be predictable (see MSC30-C. Do not use the rand() function for generating pseudorandom numbers).
Noncompliant Code Example (POSIX)
This noncompliant code example generates a sequence of 10 pseudorandom numbers using the random()
function. When random()
is not seeded, it behaves like rand()
, thus produces the same sequence of random numbers at different calls.
...