Skip to content

Instantly share code, notes, and snippets.

@paxswill
Created October 5, 2011 00:26
Show Gist options
  • Save paxswill/1263260 to your computer and use it in GitHub Desktop.
Save paxswill/1263260 to your computer and use it in GitHub Desktop.
Demonstrate the dangers of calling rand() without calling srand().
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
/*
* Require C99
*/
#if __STDC_VERSION__ < 199901L
#error C99 Required
#endif
int main(int argc, char ** argv){
/*
In all references I have checked, the default seed for the PRNG
in C is the number 1.
*/
printf("Unseeded\n");
for(int i = 0; i < 5; i++){
printf("\trand[%d] = %d\n", i, rand());
}
/*
Common practice is to seed the PRNG with the current time. This
ensures that the numbers generated are different for each program
execution, assuming each execution occurs at least one second apart.
*/
srand(time(NULL));
printf("\nSeeded with current time\n");
for(int i = 0; i < 5; i++){
printf("\trand[%d] = %d\n", i, rand());
}
/*
Here the PRNG is seeded with the number 1, showing that the
sequence generated is identical to that generated befiore srand was
called.
*/
srand(1);
printf("\nSeeded with 1\n");
for(int i = 0; i < 5; i++){
printf("\trand[%d] = %d\n", i, rand());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment