getRandomNumber()

Background

There’s an old XKCD comic about a getRandomNumber() function that I was reminded of recently:

The original is available over here.
A C function named get random number that always returns 4, with a comment noting that the number 4 was chosen by a fair dice roll and is guaranteed to be random.

I was reminded of this while reading about the new(ish) #embed preprocessor directive added to C23 and C++26. That new directive simplifies the inclusion of binary data in C/C++ code by making the preprocessor deal with the embedding, rather than a standalone tool such as xxd -i. It’s primary use, as far as I can tell, is to embed small binary assets like icons into code to avoid needing to load another file at runtime. It’s definitely not intended to be used to write an XKCD-style random number generator.

But it can be.

The Function

uint8_t getRandomNumber()
{
  return
    #embed </dev/random> limit(1)
    ;
}

On Unixy platforms with a /dev/random device file, this returns a random number, selected at compile time, in the range [0,255]. Printing the results of that function, it’s pretty clear this works as you’d expect:

$ gcc embed-random.c 
$ ./a.out 
139
$ ./a.out 
139
$ gcc embed-random.c 
$ ./a.out 
31
$ ./a.out 
31

There’s absolutely no reason to ever do this, but hey, it was fun for a few minutes, and I got to toy around with the new #embed directive a decade before I’ll be able to use it in any production system.