In C++20, what does std::format return, and why is it safer than printf for building a game server's status line?
answer
- returns a string, not a count
- argument types travel with the call
- format string checked when compiling
- printf trusts the conversion letters
basics
~20 sstd::format returns a std::string built from {} replacement fields. It knows every argument's type, and a literal format string is checked against those types at compile time, while printf trusts its conversion letters and misbehaves at run time on a mismatch.
solid answer
~40 s`std::format` (C++20, header `<format>`) takes a format string such as `"{} has {} players"` plus arguments and returns a `std::string`. Each `{}` is a replacement field; the argument's type comes from the call itself, so a `std::string`, an `int` or a `double` each print correctly with no `%s`/`%d`/`%f` letters to keep in sync. The format string is a `std::format_string<Args...>` whose constructor is `consteval`, so a field that does not fit its argument (`{:d}` for a string, a missing argument) stops compilation. `printf` instead reads its variadic arguments by trusting the conversion letters: a mismatch compiles, at most with a `-Wformat` warning, and is undefined behaviour at run time. It also cannot take a `std::string` without `c_str()`.
code
cpp · 17 lines#include <cstdio>
#include <format>
#include <iostream>
#include <string>
int main() {
std::string server = "eu-west-3";
int players = 118;
std::string line = std::format("{} has {} players", server, players);
std::cout << line << '\n';
std::cout << std::format("{1} <- {0}", "first", "second") << '\n';
std::cout << std::format("{{literal braces}} {}", true) << '\n';
// printf: the letters must match and std::string needs c_str()
std::printf("%s has %d players\n", server.c_str(), players);
}go deeper
Recall that std::format returns a std::string, uses {} fields, and that a mismatched field is a compile error, not a runtime surprise.
Explain the mechanism: a variadic template keeps the argument types, and the consteval constructor of std::format_string parses the literal against them.
Show where checking stops: runtime format strings through std::vformat, negative dynamic widths, throwing user formatters, and allocation, plus format_to for hot paths.
Weigh the C++20 library requirement and the string allocation against printf's lack of safety when choosing an output convention for a team.
## What std::format does `std::format` arrived in **C++20** in the header `<format>`. It takes a **format string** and a list of arguments and returns a brand-new `std::string` (or `std::wstring` for a wide format string): ```cpp std::string line = std::format("{} scored {} points", player, score); ``` Each pair of braces is a **replacement field**. Text outside the braces is copied as is; each field is replaced by the next argument, formatted according to its type. Nothing is printed: you decide where the string goes, whether that is `std::cout`, a file, a socket or a log buffer. ## Why printf is not type-safe `printf` is a C variadic function. It receives its arguments without their types, and the only description of what was passed is the format string you wrote: - `%d` tells it to read an `int`, `%s` a `const char*`, `%f` a `double`. If the argument is something else, the behaviour is **undefined**: garbage output, a crash, or a read of the wrong register. - It has no conversion for `std::string`. You must remember to pass `name.c_str()`. - Swapping two arguments still compiles. Compilers such as clang and GCC can warn about it with `-Wformat` when the format string is a literal, but it is only a warning, and they cannot check a format string held in a variable. A status line such as `printf("%d players on %s", server.c_str(), players)` compiles, and clang only prints a warning. Its behaviour is undefined: `printf` will try to read a pointer where it expects an `int` and an `int` where it expects a pointer, and no output it produces can be relied on. ## How std::format knows the types `std::format` is a variadic **template**, so the compiler knows the exact type of every argument. The first parameter is not a plain string but a `std::format_string<Args...>`. Its constructor is `consteval`: it runs at compile time, parses the literal, and checks every replacement field against the matching argument type. If a field is wrong, the call is not a constant expression and the program does not compile: ```cpp std::format("{:d} points", player); // player is a std::string: compile error ``` That check was added in 2021 as a fix applied to C++20. The very first C++20 wording threw `std::format_error` at run time instead, and that still happens today when you deliberately pass a runtime format string through `std::vformat`. ## Replacement field basics - `{}` takes the next argument (**automatic indexing**). - `{0}`, `{1}` choose an argument by position (**manual indexing**), so the same value can appear twice or out of order. - Mixing `{}` and `{1}` in one string is not a valid format string. - `{{` and `}}` print literal braces. - A colon starts a format specification: `{:>8.2f}` sets alignment, width, precision and type. - `bool` prints as `true`/`false`, `char` prints as a character, and a `double` with no specification prints the shortest text that reads back as the same value. ## printf, iostreams and std::format side by side | Concern | `printf` | `std::cout <<` | `std::format` | |---|---|---|---| | Type safety | none; letters must match | yes, by overloading | yes, checked at compile time | | `std::string` argument | needs `c_str()` | yes | yes | | Layout in one place | yes, one format string | no, scattered manipulators | yes, one format string | | Result | writes to a C stream | writes to a stream | returns a `std::string` | | User types | not extensible | `operator<<` | `std::formatter` specialization | | Locale | the global C locale | the stream's locale | locale-independent unless `L` is used | ## What to know about the cost and the alternatives 1. `std::format` allocates the `std::string` it returns. When you already have a buffer, `std::format_to(std::back_inserter(buf), ...)` appends to it, and `std::formatted_size` tells you the length first. 2. It needs a C++20 standard library that ships `<format>`: libstdc++ from GCC 13.1, for example. Many codebases still on C++17 cannot use it. 3. **C++23** adds `std::print` and `std::println`, which format and write in one call. For C++20, `std::cout << std::format(...)` is the usual idiom. For a junior interview, the core answer is short. It returns a string, it uses `{}` instead of conversion letters, and the compiler, not the run time, catches a field that does not match its argument.
- If std::format checks the format string at compile time, can it still throw?Yes. `std::format_error` is thrown when a format string reaches the library unchecked, through `std::vformat` with a runtime string, or when a dynamic width argument is negative. A user-defined `std::formatter` may throw from its own `format`. Allocation failure reports `std::bad_alloc`. The compile-time check covers the literal's syntax and its fit to the argument types, not every runtime value.
- How do you avoid allocating a new std::string on every call?Use `std::format_to` with an output iterator into a buffer you reuse, such as `std::back_inserter(buf)` on a `std::string` you `clear()` each time, or `std::format_to_n` into a fixed `char` array. `std::formatted_size` returns the length the output would have, so you can size a buffer first.
- std::format prints to standard output like printf does
- Uses %d and %s conversion letters inside the format string
- A printf type mismatch is caught by the compiler as an error
- std::format is available in C++17 under std::experimental
- A wrong replacement field always throws std::format_error at run time
Assumes C++20 for std::format; the compile-time format string check was a 2021 fix applied to C++20, and std::print needs C++23.