bhylu.com

Advertisements

C Random Numbers

Seed a small simulation once and test a range invariant without promising a cross-platform random sequence.

How it works

rand produces a pseudo-random integer from zero through RAND_MAX. srand selects its generator state. A fixed seed is useful for a repeatable simulation on one implementation, but C does not require the same numeric sequence across different libraries. Reducing a result with a remainder can introduce distribution bias. This demonstration checks only that a toy selected station is within a range; it is not a statistical sampling algorithm or a cryptographic construction. Security tokens need a documented operating-system cryptographic source.

Run it locally

Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.

cc -std=c17 -Wall -Wextra -Wpedantic -Werror randomness.c -o lesson

On Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.

Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.

Example

C17 · randomness.c

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

int main(void) {
    srand(17u);
    unsigned station = (unsigned)rand() % 5u;
    printf("Station in range: %d\n", station < 5u);
    return 0;
}

Expected result

Station in range: 1

The output reports the portable invariant rather than an implementation-specific station number. Seeding happens once, before the draw. Repeatedly reseeding from a coarse current timestamp can create identical short sequences. A real fair sampling procedure should use a vetted bounded-generation method or suitable library and document its reproducibility and distribution requirements.

For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.

Advertisements