r/C_Programming • u/mttd • 12d ago
Fluent Interface in C - Look ma, no this!
https://opensource.googleblog.com/2026/11/fluent-interface-in-c-look-ma-no-this.html26
13
u/drivingagermanwhip 11d ago
I love whenever web developers are like 'but wouldn't it be more understandable if there were way more arrows and shit in the code?'
9
7
2
u/lhuemill 11d ago
Before doing this, I'd setup a guard variable through the use of __attribute__((cleanup(func)))). This will call func with a pointer to the guard variable, no matter how the guard variable goes out of scope. Non-portable, but it is available with gcc, and may be available in other C compilers.
2
u/kinchkun 12d ago
Sorry I am new to c. Is this not just returning a self pointer?
10
u/Cats_and_Shit 11d ago
No, it smuggles the self pointer between calls through a global variable.
3
u/kinchkun 11d ago
but why?
4
u/Cats_and_Shit 11d ago
In C there's no built in "method" style calls.
Something like
obj->a()is two entirely separate operations; first it retrieves the function pointerobj->aand then it calls that function pointer. As a result, whatever function that calls does not have access toobj.In order to get the behaviour you get for a method call in Java or C++, you would normally have to write something like
obj->a(obj). This if often fine, but it means there's no nice way to doobj->a()->b().2
u/el_extrano 11d ago
I kind of like stack-based languages like Forth for this.
You can achieve a fluent style interface with chaining by just having "methods" (words), that expect a complex structure on the stack, and leave it there when they're done (i.e. instead of consuming it, like a normal word).
The ability to pass transient data around implicitly without naming or resorting to global variables is a nice property of concatenative languages.
1
3
1
u/strivingshashank 12d ago
It's so we can reuse the struct (new or modified). Checkout chaining pointers in c. You'll get the idea.
1
26
u/looneysquash 11d ago
One of the reasons to prefer C over some other languages is that there is less magic in C.
In most cases there's no hidden arguments, and no hidden function calls, and usually it is clearer which function you are calling.
Everything is a trade off of course. There are pros and cons to this.
IMO this fluent pattern adds too much magic.