Baffour Kusi Frimpong’s Post

📅 Day 12: 𝒑𝒓𝒊𝒏𝒕𝒇 is 53 years old. cout chaining is an eyesore. C++20 finally fixed string formatting. We've all written it. The cout chain that wraps across three lines just to print two values. Or the 𝒑𝒓𝒊𝒏𝒕𝒇 format string, where a single wrong specifier %𝒅 instead of %𝒍𝒅 silently corrupts your output or crashes at runtime. No compiler warning. No type checking. Just undefined behavior waiting to happen. 𝒔𝒕𝒅::𝒇𝒐𝒓𝒎𝒂𝒕 lands in C++20 and changes everything. Python-style {} placeholders, fully type-safe, no format specifiers to memorize. The compiler knows what type you're passing. It formats it correctly. End of story. And it's not just cleaner, it's faster. iostream carries significant overhead from locale handling and the synchronized stream machinery. 𝒔𝒕𝒅::𝒇𝒐𝒓𝒎𝒂𝒕 skips all of that. Benchmarks consistently put it ahead of cout for string construction, often significantly. 🧠 Key insight: printf is unsafe because the format string and the arguments are disconnected, and the compiler can't match them. 𝒄𝒐𝒖𝒕 is safe, but composing output is syntactic noise. 𝒔𝒕𝒅::𝒇𝒐𝒓𝒎𝒂𝒕 gives you the readability of one and the safety of the other, with better performance than both. Worth knowing: 𝒔𝒕𝒅::𝒇𝒐𝒓𝒎𝒂𝒕 returns a 𝒔𝒕𝒅::𝒔𝒕𝒓𝒊𝒏𝒈. Use 𝒔𝒕𝒅::𝒑𝒓𝒊𝒏𝒕 (C++23) to write directly to stdout without constructing one. Format specifiers still exist for precision and alignment {:.2𝒇}, {:>10}, but you only reach for them when you need them. · Custom types can opt in via a 𝒔𝒕𝒅::𝒇𝒐𝒓𝒎𝒂𝒕𝒕𝒆𝒓<𝑻> specialization of your types, your formatting rules. · Not on C++20 yet? The {𝒇𝒎𝒕} library is the identical open-source predecessor. Same API, drop-in ready. Write format strings that read like sentences. Not code that reads like noise. Day 12 of my C++ deep-dive series. Missed Day 11? Go check out the composition over inheritance breakdown. Still on printf or cout in your codebase? What's blocking the move to 𝒔𝒕𝒅::𝒇𝒐𝒓𝒎𝒂𝒕? 👇 #cpp #cplusplus #cpp20 #programming #softwareengineering

  • text

Internationalization would like to have a word... Often messages in other languages will require a reordering of the substitutions. Both printf and this new way will continue to fail in a multi-lingual program. Still, swing and a miss as far as I'm concerned.

To view or add a comment, sign in

Explore content categories