C Until It Is No Longer C
By Artyom BologovWe have to admit that C is inherently/potentially ugly. One can try making it prettier, but there's only so much one can do to C without compromizing its nature. That's what I'm going to do here—stretching the limits of what C is, introducing some prettier things. If you're a C programmer (like me), you might end up horrified by what I'm doing. Otherwise, sit back and watch how readable C can become!
Standard Headers: Booleans and Nicer Logic
C23 made booleans part of the language. Which is a good direction. But what if I don't want to wait for C23 to be rolled out in GCC or Clang? Well, I can always define some booleans myself!
Et voilá! Now we can do proper booleans:
Yes, implicit conversion to booleans. Because booleans are nothing but unsigned integers 1 and 0. Now what doesn't work for me is this ugly double vertical bar. I want some Pythonesque boolean logic!
It turns out I can have this nicer boolean logic, just one #include
away!
I'm also defining some missing bits and fixing the inconsistently named
xor
and compl
.
With these, iscontrol
becomes even more readable!
eq
feels sligtly off here.
Why not define another macro for it?
A couple of macros, actually.
And use it like:
Notice that I switched the order of arguments to a more intuitive one.
Putting a constant before the equality operator is no longer necessary.
(C programmers do that to avoid typos like c = 127
,
relying on compiler to scream when it sees 127 = c
.)
After all, the spelled-out operator cannot end up as assignment.
Readability and reliability win.
Nicer Types: Fixed Width and Custom Shortcuts
But it never hurts to use these more:
And then, we can go even further, inspired by brevity of uint8_t
:
Going even further, here are some more Go-inspired types:
Type Inference
Another nice-but-not-quite-C thing C23 added is... type inference! You may disagree with this decision, but it certainly is nice to have. So let's add it:
And use it too!
Okay, I should probably stop here. Both because the example is no longer improvable. And because most of the readers are already hemorrhaging. Sorry! I could've promised I won't do it again, but alas. Have a good rest of the day with this newly acquired phobia.
Oh and check out Pretty.C, my project making C even further from God!