4 ms·
> Current compilers warn you if the format string doesn’t match its arguments. But this only works on functions that have the same signature as printf so it doe
by kevin_thibedeau 2y ago
> Current compilers warn you if the format string doesn’t match its arguments. But this only works on functions that have the same signature as printf so it doesn’t work on my implementation.
GCC has the format attribute that lets you have printf type checking on your own variadic functions:
https://gcc.gnu.org/onlinedocs/gcc-14.2.0/gcc/Common-Function-Attributes.html#index-Wformat-3 https://gcc.gnu.org/onlinedocs/gcc-14.2.0/gcc/Common-Functio...
- WalterBright 2y agoSo does D: https://dlang.org/spec/pragma.html#printf https://dlang.org/spec/pragma.html#printf It was a huge win, at least for me. I implemented it because I was really sick of mismatches. (Although I was careful to use the right formats, when refactoring I'd change a type and then the printf's would go awry. Having the compiler flag them made for quick fixing.)
- norir 2y agoFormat strings are a technique that I think largely should be left behind anyway. String interpolation is in my experience usually shorter, easier to read and will always be checked by the compiler.
- jonhohle 2y agoIt’s shorter until you need any type of formatting. It’s hard to get more terse than `%8.2f`.
- gizmo686 2y agoYou can do that with string interpolation too. In python it would be: print(f"{foo:8.2f}") compared with C-style printf: printf("%8.2f", foo)
- rowanG077 2y agoAlso hard to be more cryptic. The amount of times I regoogle that syntax, or what exactly those numbers mean is basically uncountable.
- samatman 2y agoZig builds string formatting at comptime, so if the format string doesn't match the arguments, the program won't compile. It's nice.