Can C be Object Oriented? Yes!
Object-oriented languages like Python, Java, Rust, or C++ offer native object methods and automatic object lifetime cleanup, enabling chain operations on data structures, so you can call obj->a()->b()->c() and each method knows what it's working on. These fluent interfaces are common to many libraries that streamline configuration and reduce boilerplate. Let's take a look at an example:
ChSlice *mid = ch_new_String("One_Two_Three_Four")
->append("_Five_Six")
->split("_")
->sub_slice(1, 4);
puts(mid->generic.to_chars()); /* ["Two","Three","Four","Five"] */
ch_release(mid);
This chain of functions takes a string, appends it to another string, splits it into an array, and slices the array in one chain of function calls. It's a pretty basic demonstration of using fluent interfaces for building a data structure with method chaining. But if I told you this was plain ANSI-C, you would think I committed a preprocessor felony and leaked three heap allocations along the way. And there are two big reasons why:
- There are no objects in C. No member variables or methods. No
thisorselfto reference your object's data. The functionappend("_Five_Six")has no attached state, seeing only a single string literal and whatever is global. - There is no garbage collector. In standard C, chaining heap allocations together without saving each intermediate pointer to a variable and freeing it by hand inevitably results in a memory leak.
Manipulating strings and collections in C usually means threading state through standalone functions (str_append(s, ...)), holding onto every intermediate pointer, and freeing each temporary buffer by hand. We built iso-c-chaining to explore how far we could push fluent method chaining and automatic temporary cleanup using only standard ISO C. Here is how the library appends to a string, splits it on a delimiter, and takes a sub-slice of the resulting array in a single expression.
This code does exactly like you would expect in a modern language. It allocates a string and some kind of array, manipulates them both without a byte leaked, and cc -E shows the preprocessor never touched it. In fact, every C feature powering that chain has been part of the language since 1989 ANSI C (C89).
Party like it's 1989
Let's kick this up a notch. Take a kind of map, put another map inside it, and see what happens. That would surely break this no-leaking-or-preprocessor-tricks little C89 exercise. Well, it's time to party:
ChHash *user = ch_new_Hash(3)
->put("name", ch_new_String("Ada"))
->put("role", ch_new_Hash(2)
->put("title", ch_new_String("Engineer"))
->put("level", ch_new_Number(5)))
->put("active", ch_new_Boolean(1));
puts(user->generic.to_chars());
/* {"name":"Ada","role":{"title":"Engineer","level":5},"active":true} */
ch_release(user);
These put() calls are being asked to unravel the chain inside the chain of a map inside a map. Where is it going to find the right container? And now there are Strings and Numbers and Booleans, oh my!
How? You might remember: functions in C only see their arguments and whatever is global.
1. Scoping with static
C's static keyword does two different jobs depending on where you put it, and self() uses both at once:
static String* self(String *s) {
static String *slf = NULL;
if (s != NULL) {
slf = s;
}
return slf;
}
The outer static scopes self() to the file (the type's .c implementation), but the inner static keeps slf around in every call. We cleverly use NULL to just retrieve the existing value, since we should never be setting our self pointer to NULL.
2. Casting generics
Since struct pointers in C can be cast as their first field, we take advantage of that to give us a baseline of functionality for our types:
struct ch_generic_el {
int refs;
void* (*bind)(ChGenericEl *);
void* (*save)(void);
void (*del)(void *);
char* (*to_chars)(void);
};
Putting ChGenericEl first in every struct lets put(char *key, void *val) accept a String*, Number*, Boolean*, or Hash*, cast it to ChGenericEl*, and call to_chars() or del() without caring which type it is.
3. Stacking chains
A single slf pointer works until you build a Hash inside another Hash, where the inner Hash would overwrite the outer one. Adding prev_self and next_self pointers to ChGenericEl turns each type's self() into an intrusive stack:
if (s == (ChGenericEl*)-1) {
*top_ptr = top->prev_self;
} else if (s != NULL && s != top) {
s->prev_self = top;
*top_ptr = s;
}
return *top_ptr;
Constructing the inner Hash pushes it on top of the outer Hash so .put("title", ...) and .put("level", ...) target the inner map, while passing -1 pops it back off. (And in C11, adding _Thread_local to top gives every thread its own independent stack.)
4. Counting garbage
And what about all those potential memory leaks? We're making elements mid-chain that get consumed before the chain is finished. Here we turn to the old classic: reference counting, but with a twist: Every new object starts with refs = 0, meaning nothing owns it yet. If a method like split() or sub_slice() consumes an object whose refs is still 0, it frees that temporary on the spot before returning the next link in the chain.
And when a container method like put() receives an element, it claims ownership:
if (elem == container_slf || el->refs == 0) {
el->bind((ChGenericEl*)-1);
}
el->refs++;
Note that this means ephemeral objects are automatically released, so the caller needs to bind them manually if the ephemeral object is needed after the chain is complete.
Because the inline Hash enters put() with refs == 0:
el->bind((ChGenericEl*)-1)pops the finished innerHashoff theHash selfstack, restoring the outerHashto the top so.put("active", ...)targets the outer map.el->refs++transitions the element from an unowned temporary (refs == 0) to a container-owned value (refs == 1). That keeps consuming methods from freeing it mid-chain if you later retrieve it withget(), and lets an element be shared across multiple containers or variables—each owner incrementsrefs, andch_release()decrementsrefson every child in the tree, freeing each object only when its last reference drops to0.
Now what can we do with this?
You might be thinking, "Wow, we could use this for all kinds of wonderful projects!" We chose a webserver instead:
ch_new_Server(8080)
->get("/users", list_users)
->get("/users/:id", get_user)
->post("/users", create_user)
->put("/users/:id", update_user)
->delete_route("/users/:id", delete_user)
->listen();
Each callback receives the parsed HTTP request: URL :id parameters, query string, and parsed JSON body. This is packaged as a Hash*, and whatever object the callback returns gets serialized to JSON (to_chars()) and freed automatically after the response is sent.
Here is what list_users looks like when wired up to a SQLite Db object:
static GenericEl* list_users(Hash *req) {
return (GenericEl*)$(db)
->params($(req)->get("query"))
->query("SELECT id, name, role, score FROM users "
"WHERE (:role IS NULL OR role = :role) "
" AND (:min_score IS NULL OR score >= :min_score) "
"ORDER BY score DESC");
}
What comes back from ->query(...) is the rare combination of everything we built above: a Slice of Hashes holding Numbers and Strings as database result rows. Because every one of those types shares ChGenericEl, the server just calls to_chars() on the returned Slice to stream out [{"id":1,"name":"Alice","role":"admin","score":98.25}, ...] and releases the entire result tree in a single call once the response is sent.
Wait, what's with the $?
In our earlier examples, every chain started with a ch_new_* constructor. Inside list_users, however, db and req are already-existing objects, so before calling ->params(...) or ->get("query"), we need to reference our previously created elements by calling their bind() function pointer: db->bind((GenericEl*)db).
Nobody wants to type db->bind((GenericEl*)db) at the start of every statement, so the library provides four tiny one-line convenience macros:
$(obj)expands to((obj)->bind((ChGenericEl*)(obj)))which binds a previously created variable so you can start chaining on it.->$$expands to->generic.save()which bumpsrefs(refs++) at the end of a chain when you want to keep an object in a variable (db = create(Db, ":memory:")->...->$$;) instead of letting the chain consume it as a temporary.create(Type, ...)expands toch_new_Type(...).->chars()expands to->generic.to_chars().
Pulling back a little performance
You might look at this and think, "Wow, this is wrapping every single int in an object like it's a horrible java.lang.Integer." And you would be right, but we can take a page from JavaScript's TypedArrays and not have a bunch of function pointers attached to every element, giving us back the performance we expect from C:
TypedIntArray *scores = create(TypedIntArray, 0)
->push_n(6, 42, 15, 88, 23, 16, 4)
->sort()
->$$; /* [4, 15, 16, 23, 42, 88] */
Now a single TypedIntArray object wraps a raw contiguous int* buffer, so a massive array of integers isn't attached to an even more massive number of function pointers. TypedIntArray, TypedCharArray, and TypedFloatArray are included by default (and can be sorted, mapped, filtered, sliced, and dropped straight into a Hash for JSON serialization), or you can declare one for any fixed-width type with CH_DECLARE_TYPED_ARRAY.
In examples/chain_vector_db.c, TypedFloatArray stores 256-dimensional embedding vectors for over 4,000 Linux whatis man pages in SQLite—computing each vector's norm in a single map + reduce chain:
double norm = sqrt($(vec)
->subarray(0, vec->length)
->map(square_double)
->reduce(add_doubles, 0.0));
Try it out
We've released iso-c-chaining as an open source demonstration library under the Apache 2.0 license for C developers to explore, tinker with, or drop into side projects via its single-header build (chain_single.h). The full source, including TypedArrays, the JSON parser/serializer, and the SQLite/HTTP server examples, is available on GitHub at google/iso-c-chaining. Contributions and feedback may be given on the GitHub project directly.

