u/WittyStick

TIL glibc lets you add custom ((v)f)printf format specifiers.

TIL glibc lets you add custom ((v)f)printf format specifiers.

I had a need for an extended printf, and found that rather than writing my own, glibc lets you register your own specifiers with register_printf_specifier.

I made a simple demo for printing bool as it kind of annoys me to have to type printf("%s", value ? "true" : "false"), and I don't like using integers to represent booleans. (This wasn't my goal, but it's the simplest type to demonstrate).

Now can type printf("%?", value) to print true or false. Works will all the *printf style functions.

Has an alt (#) representation, which is uppercase TRUE or FALSE - ie: "%#?".

And I also added width specifiers for easy alignment. You can specify some padding with "%n?" - right aligned by default, with "%-n?" aligning left. Could probably extend to support * also with extra argument for width.

Demo in godbolt

Just thought others may find this interesting.

EDIT : Have been corrected and this also works with *sprintf functions.

u/WittyStick — 4 days ago