A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
rand generates a pseudo-random integer between 0 and RAND_MAX. It is deterministic. Given the same seed, it produces the same sequence every time. srand sets the seed. If you do not call srand, the default seed is 1, and your program produces the same "random" numbers on every run. The standard rand is not suitable for cryptography, simulations requiring statistical quality, or anything where predictability is a risk. It is fine for games, shuffling, and simple sampling.
#include <stdio.h>#include <stdlib.h>#include <time.h>int main(void) {printf("Unseeded (always same):\n");for (int i = 0; i < 5; i++) {printf(" %d\n", rand());}srand((unsigned int)time(NULL));printf("\nSeeded with time:\n");for (int i = 0; i < 5; i++) {printf(" %d\n", rand());}printf("\nRAND_MAX = %d\n", RAND_MAX);return 0;}
#include <stdio.h>#include <stdlib.h>#include <time.h>int rand_range(int min, int max) {return min + rand() % (max - min + 1);}int main(void) {srand((unsigned int)time(NULL));printf("Dice rolls: ");for (int i = 0; i < 10; i++) {printf("%d ", rand_range(1, 6));}printf("\n");return 0;}
The modulo approach has a slight bias when RAND_MAX + 1 is not evenly divisible by the range size. For a six-sided die with RAND_MAX of 2147483647, the bias is negligible. For cryptographic or simulation work, it matters. The proper fix is rejection sampling: discard values above the largest multiple of the range that fits in RAND_MAX.
Never use rand() for security-sensitive purposes: session tokens, password salts, cryptographic keys, nonces. The output is predictable. An attacker who observes a few values can reconstruct the internal state and predict all future values. Use /dev/urandom on POSIX, BCryptGenRandom on Windows, or a vetted library like libsodium.
rand is a teaching tool and a game utility. It is not a security primitive. Know its limitations. Seed it deliberately. Use it for shuffling and sampling. Use /dev/urandom for anything an attacker might care about. Next: memccpy, a bounded copy that stops at a delimiter byte.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.