Tech News
← Back to articles

Generic Containers in C: Safe Division Using Maybe

read original related products more articles

Generic Containers in C: Safe Division Using Maybe.

Martin Uecker, 2025-08-10

I discuss the implementation of type and bounds safe generic containers in C. Previously, I discussed a span type, bounds checking using arrays. and a a vector type.

This time, I will discuss maybe inspired by Haskell. This type can used to return a value that may not exist, e.g. because an error was encountered during the computation. The following examples shows for a divide function that catches division by zero.

static maybe(int) divide(int a, int b) { return (b != 0) ? maybe_just(int, a / b) : maybe_nothing(int); }

But careful, there is another error case not checked here! Which is it?

... continue reading