r/ProgrammingLanguages • u/aalmkainzi • Apr 10 '26
Question about using % as the a format character in printf-like function
I'm working on a string library, and wanted to implement a printf-like API, but type-safe.
I implemented it like this:
cgs_format_append(stdout, "% + % = %", 2, 3, 5);And I made the escape be `%%`. But now the problem is how do I format two args next to each other?
cgs_format_append(stdout, "%%", 20, 26);this won't work because the format character is escaped, and a single % is printed.
Is this the reason other langs use two different characters for formatting (e.g. {}, %d, etc.)?
Apparently, Jai (unreleased programming lang) uses a single %, based on this page, but it isn't mentioned how it handles formatting two args next to each other.
Is there an obvious syntax I can use and still keep it %, or should I just change it to {}
11
u/lucidbadger Apr 10 '26
Change your escape to
\%or something like that2
u/DeWHu_ Apr 10 '26
No, to print
"%d=10"(where 10 is arg) you would still need to escape the first%d. C used indicator char (%) plus type indicator only because of performance. Newer formatters (eg. Py f-string) use braced indication ({}) for readability and more formatting options.If your design is to pass to formatter type prepared arguments, you can absolutely use a single char indicator, but at this point why not use a "string join"?
2
u/Mercerenies Apr 11 '26
If you're trying to keep the C-style syntax, I'd just unconditionally use
%sfor all formats and%%for literal percent. This is basically how Godot does it (you can use the other format primitives in GDScript, but you only need them if you want to do things like%.2fto print two decimal places).I am curious how you're planning to make this type-safe in the confines of C. C++ has variadic templates, and "type-safe printf" is practically the tutorial for them. Zig has comptime, and Rust approximates comptime with a fairly sophisticated
println!macro. But down in C, you're stuck with good old-fashionedva_args, which is.... inherently very unsafe.3
u/Ninesquared81 Victoria Apr 10 '26
How do you actually format with your formatting function? How could I print a number in hexadecimal, for example? The answer probably lies there.
4
u/tandycake Apr 10 '26
I don't think there is a way around it. You either need to use a different escape character (like backslash), use two characters, ignore/greedy, or provide a workaround for that specific scenario.
Basically we can't know if you want %24 here or 24%, so even a 2nd pass won't work if you have leftover params.
For a custom programming language though, you can dream up some interesting solutions to this. For example, although ugly, you could do this:
It's at compile time anyway, so you could just drop %% and require an empty arg like the above example or an unquoted %:
There are probably some novel solutions could dream up for this.
As far as Jai, I don't see any documentation on this. I think you'd have to use his compiler and see what it produces. I assume it would just print "%%" if you specify "%%%%", which is fine as a solution. And if someone needs that, they can just concat the string as a workaround: ("%",2.str + 4.str + '%'). And since it's so rare, it might be fine.
4
u/BrangdonJ Apr 10 '26
You might want to think about language localisation. Sometimes when a phrase is translated from English to foreign, the new grammar rules means the order of the arguments needs to change. This leads to format strings like:
which can be changed to:
by only changing the string. In a real app, the format string would come from a resource table or file indexed by the language, which can be updated without needing program source code.
If you do this, then using "%%" for the escape does not make any problems with two arguments next to each other.
1
u/useerup ting language Apr 10 '26
I think that printf-like functions is a dead end. I believe that you should think along the lines of string interpolation.
Strongly typed string interpolation can also be more efficient because the interpolation can be done at compile time rather than format strings being interpreted by a printf function.
With string interpolation as it is in C# your code would look like
where a=20 and b=26.
String interpolation can be resolved at compile time and lowered into a number of "append" or "concat" operations.
Java has an even more advanced template system. It allows for pluggable template processors. You may want to look at that too.
1
u/rodrigopierre Apr 22 '26
O problema aí não é tanto usar %, mas sim a ambiguidade que ele cria quando você também precisa de escape. Quando você define %% como literal, perde uma forma simples de representar dois placeholders seguidos sem confundir o parser. É por isso que o printf resolve isso adicionando especificadores (%d, %s, etc.), porque cada % já carrega contexto suficiente pra saber o que vem depois.
Se você quiser manter só %, uma saída é fazer o parser consumir sempre % + algum padrão obrigatório (tipo %{} ou %t), em vez de deixar o % “solto”. Assim você elimina ambiguidade e ainda consegue ter placeholders consecutivos sem conflito. Outra opção é separar completamente literal de formatação, tipo um token especial ou até uma lista de argumentos já estruturada.
No fim, muitas linguagens foram para {} ou similares justamente porque simplifica parsing e evita esses edge cases. Dá pra fazer funcionar com %, mas você vai acabar reinventando algo bem próximo do que o printf já faz hoje.
2
u/evincarofautumn Apr 10 '26
If you disallow escaping, you can just use formatting to emit the format character:
format("%%", 100, "%")⇒100%If you still allow escaping, you can add a way of separating the format strings so they don’t abut, like taking a tuple of format strings instead of just one:
format(("%", "%"), 20, 26)⇒2026Also, nothing says a string literal has to represent a Unicode string. For example, if you have a way of writing an empty character, you can use that as a separator:
format("%\,%", 20, 26)⇒2026. This is similar to but distinct from an empty string escape like Haskell’s"\&" == "", although they serve a similar purpose of distinguishing e.g."\x2026"="…"and"\x20\&26"=" 26".1
u/Jaded_Following2089 Apr 10 '26
I got curious about how this works under the hood and realized that
printfavoids this by treating%strictly as an initiator that must be terminated by a type specifier (e.g.,%d,%s). Consequently,%d%dunambiguously defines two separate token boundaries, which is very interesting1
u/Key_River7180 Nain. Apr 11 '26
%% is used in libc formats for this, but since it doesn't work for this, you can always use % for this
1
u/SirPigari Apr 11 '26
You could switch from single fmt char to two, like for example %$
1
u/WittyStick Apr 10 '26
In C, adjacent strings are automatically concatenated with any middle nul-terminators removed.
"%" "%"ends up as"%%\0".