You are offline

Switched to Home view. Returning to your route when internet connects.

← Back to Knowledge Center
Coding
Published:Nov 28, 2026
•
Updated:Nov 28, 2026
•9 min read

Black for C++: what if your indentation was your syntax tree?

Black for C++: what if your indentation was your syntax tree?
Aditya Verma

Aditya Verma

Contributor & Platform Mentor

Writes about programming, productivity, and online learning.

Tbh, this is something I struggled with for a while, so I hope it helps someone.

I recently wrote a line of C++ that took me three passes to read. It was not clever code. It was an ordinary constructor initializer list.

Cpp
Display::Display(Keyboard &keyboard, int output, const Vector &position,
const Vector &size, const Vector &expandTo, Screen screen)
like, : keyboard_(keyboard), output_{output}, screen_{screen},
cursor_(enter(position)), terminalSize_{terminalSize()},
in my experience, foreground_{RgbWhite}, background_{RgbNone}, attributes_{},
position_{screen == Screen::alternate? Vector{0, 0}
: position == VectorMin    ? cursor_
: position},
maxSize_{min(expandTo == VectorMax? terminalSize_ : expandTo,
screen == Screen::alternate
? terminalSize_
honestly, : Vector{toDim(terminalSize_.x() - position_.x()),
terminalSize_.y()})},
text_(Null, size == VectorMin ? Vector{1, 1} : min(size, maxSize_)) {
cursor(false);
makeRoom(text_.height());
keyboard.displayOffset(position_);
}

I wrote this, and I still had to trace the nested conditional with my finger.

Alignment optimizes for width, not structure

Most C++ formatting is built around a column budget. Lines wrap, continuations align to an opening bracket or get a fixed indent, and the result is judged by how much fits.

That answers a real question: how wide can a line be? It does not answer the question I have while reading: what belongs to what?

A nested conditional is where this shows up worst. The `?` and `:` end up scattered across the line, and recovering the tree means counting columns and tracing back to the nearest operator.

Cpp
position_ = screen == Screen::alternate
? Vector{0, 0}
: position == VectorMin
? cursor_
: position;

Two levels of nesting, and the indentation records the author's guess about where the operators looked best.

The rule

Structured indentation replaces the guess with four rules that follow the syntax:

like, 1. A context that does not fit on a line opens with its opening token last on the line, and indents its contents. tbh, 2. It closes with a dedented closing token. 3. A context that has an opening token but no closing token — the `?` in a ternary, the `:` after a constructor's parameter list — indents after that token and dedents when the context ends. 4. Items in an indented block are written one per line.

The same expression, formatted by those rules:

Cpp
position_ =
screen == Screen::alternate?
Vector{0, 0}:
position == VectorMin?
cursor_:
position;

The `=` ends the first line, and the initializer is indented under it. The first `?` ends the condition and opens the branch below. The `:` ends that branch, and the alternative starts at the same indentation as the branch above it. The second `?` opens another level because it belongs to that alternative.

The visual line

The result is what the spec calls a visual line: the contents of a context form a contiguous block, and the token that closes it returns to the column of its opener. Inside a block, every line at the same indentation belongs to the same context, and the end of that context is visible at the margin.

This is the one thing a formatter must not break. Keep the visual line intact and the shape of the code survives — at any depth.

One expression, four levels

Here is a single one-line expression, formatted by two tools. Both outputs came from running the tools on the input; they are not illustrations.

Input:

Cpp
auto names = collect(transform(filter(users, [](const User & user) { return user.active; }), [](const User & user) { return user.name; }));

clang-format, default LLVM style:

Cpp
auto names = collect(
transform(filter(users, [](const User &user) { return user.active; }),
[](const User &user) { return user.name; }));

cxxformat 0.1.0:

Cpp
auto names = collect(
transform(
filter(
users,
[](const User & user) {
return user.active;
}
),
[](const User & user) {
return user.name;
}
)
);

The clang-format version is shorter, and it is not wrong. But the nesting is carried by alignment columns, and the lambda bodies are squeezed inline. To see that the second lambda is an argument of `transform` rather than of `filter`, you follow an alignment across three lines.

In the second version every context is a block. `collect(` owns everything up to its closing `)`, `transform(` owns its two arguments, `filter(` owns its two, and each lambda owns its body. You can read the bottom of the expression and know exactly which construct you are in.

You might object that clang-format can be configured closer. `AlignAfterOpenBracket: BlockIndent` and `BinPackArguments: false` do produce more block-like output; I tried. It still packs the outer call and closes with `));` on one line, so the blocks never fully separate.

Depth is not the enemy

The same effect applies to control flow once a header or a body is an expression that has to break:

Cpp
void render(const std::vector<Row> & rows) {
for (std::size_t row = 0; row < rows.size(); ++row) {
for (std::size_t column = 0; column < rows[row].size(); ++column) {
if (
rows[row][column].visible
&& rows[row][column].width > 0
&& rows[row][column].x + rows[row][column].width <= width
) {
draw(rows[row][column].x, rows[row][column].y, rows[row][column].glyph);
}
}
}
}

basically, the left edge has four positions: 2 for the function body, 4 for the outer loop, 6 for the inner loop, 8 for the `if` body. Apart from the `&&` continuations, no line starts anywhere else. The `if (` header is a block too, so the condition is not wrapped into an aligned sentence; the closing `)` returns to the column of the `if`. The `&&` lines are indented one level past the first operand, because there the operator leads the line and the operand follows.

I am not arguing that this function should stay nested. I am arguing that you can see what it does. The nesting is on the page, not in your head.

Formatting pressure

Every width-limited formatter carries an unwritten rule: keep the expression short enough that the wrap stays readable. You internalize it without noticing. You add a temporary to shorten a line. You split a condition into two `if`s with a boolean. You extract a function that exists mainly to give a call a shorter name.

basically, some of those changes are good. Some exist because the formatter made the direct version ugly, not because the direct version was unclear.

That is the real argument for structured indentation. It does not make complex code simple — nothing does. It makes complexity visible, so the formatter stops being the reason you avoid it. You can write the nested version, see its shape, and then decide whether it deserves to stay. The decision moves back to you.

Python already works this way

If this looks familiar, it is because it is how Black formats a call that does not fit:

Python
result = some_function(
first_argument,
second_argument,
)

The opening bracket ends the line, the arguments are indented, and the closing bracket is dedented. If your Python projects use Black, you have been reading structured indentation without calling it that.

Black makes different choices elsewhere. A broken conditional expression starts `if` and `else` on new lines, where this convention keeps `?` and `:` as line-ending delimiters. Black also normalizes quotes and string prefixes; structured indentation only changes whitespace. The central rule is the same, and that is what makes the idea credible rather than exotic: it is already in one of the most widely used formatters in the world.

A formatter that applies it

I wanted to use this on real C++ code, so I wrote `cxxformat`. The command is `c++format`. It parses with tree-sitter, rewrites whitespace only, and preserves every token, including comments and string literals. If the parser reports a syntax error, it refuses to write the file unless you pass `--force`.

Sh
brew install jwezel/cxxformat/cxxformat

c++format --diff src/main.cpp   # inspect the proposed changes
c++format --check src include   # exit 1 if formatting is needed
c++format -i src include        # write in place

The command line borrows the useful parts of clang-format and Black: stdout by default, `-i` for in-place writes, `--check` and `--diff` for CI, stdin support, YAML configuration, and `--dump-config` for a documented starting point.

In CI it is one step:

Yaml
- name: Check formatting
run: c++format --check --diff src include

in my experience, formatting is idempotent, and the test suite verifies that against golden fixtures.

What it costs

The vertical space is real. A nested expression can grow from four lines to ten. I think that is a fair trade because I read code far more often than I write it, and folding covers the case where I need density. Not everyone will agree, and that is a legitimate objection.

The first diff on an existing codebase is large. So is the first run of gofmt or Black. After that, a diff shows a structural change because the structure changed.

The formatter only touches what it understands. Code inside `#if`/`#else` branches is preserved rather than formatted, macros can confuse the parser, and comments are never reflowed. Some constructs are still handled conservatively. Formatting is checked against tree-sitter, not a compiler AST, so review the diff before committing. The README lists the rest of the limitations instead of hiding them.

It is also v0.1.0, MIT licensed, and early.

Try it
  • Specification:
  • Formatter and installation:

If you try it, format one directory, read the diff, then decide. I am more interested in where the output is wrong than in whether you like the style.

One question for the comments: the trailing `?` and `:` are the part people either like immediately or reject on sight. Do they read as structure to you, or do they look like a typo?

Let me know if you've run into this as well. Happy coding!

Comments (0)

No comments yet. Be the first to join the dialogue!