skip to content

Format and Print

C++20 std::format brings type-safe, Python-style formatting checked at compile time, and C++23 std::print writes it out. Interviewers ask how it beats printf and streams.

on this pageshow

explore

questions

6

In C++20, what does std::format return, and why is it safer than printf for building a game server's status line?

level: juniorimportance: must knowfreq 62%

answer

  1. returns a string, not a count
  2. argument types travel with the call
  3. format string checked when compiling
  4. printf trusts the conversion letters

basics

~20 s

std::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
cpp
#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

for a junior

Recall that std::format returns a std::string, uses {} fields, and that a mismatched field is a compile error, not a runtime surprise.

for a middle

Explain the mechanism: a variadic template keeps the argument types, and the consteval constructor of std::format_string parses the literal against them.

for a senior

Show where checking stops: runtime format strings through std::vformat, negative dynamic widths, throwing user formatters, and allocation, plus format_to for hot paths.

for a principal

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.

open as a page

What do C++23 std::print and std::println add over writing a std::format result to std::cout?

level: middleimportance: should knowfreq 45%

basics

~20 s

std::print formats and writes in one call to a C stream, stdout by default, and std::println adds a newline without flushing. Each call writes its whole output as one operation, and Unicode text reaches consoles that need a native Unicode API intact.

open as a page

In a C++ std::format replacement field such as {:*>10.2f}, what do the fill, align, width, precision and type parts do?

level: middleimportance: should knowfreq 48%

basics

~20 s

After the colon, the asterisk is the fill character, > right-aligns, 10 is the minimum field width, .2 is the precision and f selects fixed-point notation, so 15.6249 becomes five asterisks then 15.62. Each part is optional, but the order is fixed.

open as a page

How do you make a C++ Money type printable with std::format, and what must the std::formatter specialization's parse and format members do?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Specialize std::formatter<Money>. Its parse member reads the format specification and returns an iterator to the closing brace, and its const format member writes the value to ctx.out() and returns the end iterator. Inheriting from std::formatterstd::string reuses width, fill and alignment.

open as a page

Why does std::format(tmpl, name, lobby) fail to compile when tmpl is a std::string loaded from a config file, and what do you call instead?

level: seniorimportance: should knowfreq 40%

basics

~10 s

std::format's first parameter is a std::format_string whose constructor is consteval, so it only accepts a compile-time constant it can check. For a runtime template call std::vformat(tmpl, std::make_format_args(name, lobby)) and catch std::format_error.

open as a page

How would you lead a C++ codebase's move of its logging and console output from iostreams and printf to std::format?

level: principalimportance: should knowfreq 30%

basics

~20 s

First confirm every supported compiler ships C++20 <format>. Route all output through a wrapper taking std::format_string so call sites stay compile-time checked, plan for changed number text, handle runtime templates and exceptions, and convert module by module behind tests.

open as a page