Indentation, Braces, Operator Spacing & Why-Not-How Comments
Enforce 8-column tab visual nesting alarms, K&R vs column-1 brace placement, unambiguous pointer/operator spacing, and invariant-focused block comments.
What you'll learn
- Audit embedded C11 source lines for 8-column tab visual width, K&R control braces, and aligned switch/case fallthrough annotations.
- Analyze pointer-declarator binding and operator-spacing defects that disguise non-pointer declarations or visual precedence traps.
- Evaluate multi-line block comments to replace line-by-line syntax narration with hardware and concurrency invariant contracts.
Visual Nesting Alarms and Asymmetric Brace Placement
Code inside a bootloader or Linux kernel driver is written once and audited hundreds of times during bring-up panics, race-condition reviews, and LTS backports. When each engineer invents personal spacing, 2-space indents, or brace styles, reviewers waste working memory parsing typography instead of spotting a missing spinlock release or an implicit switch fallthrough.
The Linux kernel CodingStyle uses 8-column hard tabs ('\t') deliberately as a structural complexity alarm rather than an aesthetic preference. Against an 80-column target (100-column ceiling), four nested if/for levels push code past column 32 before an expression even starts. Instead of shrinking indentation to 2 spaces to hide spaghetti state machines, you invert guard conditions early or extract single-purpose static helpers.
Figure 4.1a. 8-column tabs expose excessive cyclomatic nesting early so drivers refactor into flat guard clauses.
mental model: Think of kernel C formatting like standardized aircraft cockpit switch guards and color bands: every pilot reads control state in milliseconds without mentally translating personal layout quirks during an emergency.
Where it stops working: Formatting rules never prove algorithmic correctness on their own; clean indentation makes deeply nested bugs visible so engineers refactor control flow before shipping.
definition (8-Column Tab Complexity Alarm): Named from the Linux kernel CodingStyle chapter 1 rule equating one ASCII HT (0x09) character to eight terminal columns, the 8-column tab complexity alarm pairs wide visual steps with an 80-column soft margin so deeply nested conditionals physically run out of horizontal space, compelling the author to flatten control flow with guard clauses.
- Step 1. Hard tabs advance to multiples of 8 columns, making >3 nested levels immediately obvious.
- Step 2. Column-1 braces anchor top-level functions while K&R braces conserve vertical lines inside bodies.
- Step 3. Vertical switch/case alignment avoids double-indentation and pairs with -Wimplicit-fallthrough.
- Step 4. sizeof(*rx_buf) survives type refactors automatically without repeating struct names.
Figure 4.1b. Use 8-col tabs, K&R control braces, identifier-bound *stars, and why-not-how comments.
Brace Geometry, Operator Spacing, and Fallthrough Discipline
Every token spacing rule in CodingStyle eliminates a concrete visual ambiguity. Reserved control keywords (if, for, while, switch, return) take one space before (, visually separating control flow from function calls (spin_lock(&q->lock)). Conversely, sizeof, alignof, and typeof behave syntactically like compile-time functions and never take a space before (: write sizeof(*dev) rather than sizeof (struct my_dev) so changing the pointer's struct type never leaves a stale allocation size behind.
In C grammar, the pointer * modifier binds to the declarator, not the type specifier. Writing uint8_t* tx, rx; declares tx as a pointer and rx as a single uint8_t byte, whereas uint8_t *tx, *rx; matches the compiler's actual AST. Likewise, in multi-branch if (cond) { ... } else { ... } chains, whenever any branch spans multiple lines, every sibling branch receives braces so adding a log statement later cannot trigger a dangling-statement bug.
Figure 4.1b. Declarator-bound stars and compiler-checked fallthrough attributes turn style rules into bug prevention.
| Construct | Kernel C11 Contract | Rejected Pattern | Defect Prevented |
|---|---|---|---|
| Indentation | 1 hard tab = 8 columns (<= 3 levels) | 2 or 4 spaces hiding 6 nested if blocks | Unreadable arrow-code state machines |
| Pointer declaration | uint32_t *reg_a, *reg_b; | uint32_t* reg_a, reg_b; | reg_b silently compiled as scalar integer |
| Allocation size | kzalloc(sizeof(*priv), GFP_KERNEL) | kzalloc(sizeof (struct old_priv), ...) | Heap buffer under-allocation after type change |
| Switch fallthrough | Aligned case + __attribute__((fallthrough)) | Indented case missing break; comment | Accidental execution of adjacent reset handler |
learner@ksa:~/gl-e00/m04-l01$ bat -H 17 -H 31 coding_style_irq.c File: coding_style_irq.c // SPDX-License-Identifier: GPL-2.0 #include <stdint.h> #define UART_SR_RXRDY (1U << 0) #define UART_SR_OVERRUN (1U << 3) struct uart_port_ctx { volatile uint32_t *sr_reg; uint32_t rx_drops; uint32_t rx_frames; }; /* * Why: Clearing OVERRUN on i.MX6ULL USR2 requires acknowledging the status * bit before draining URXD; reversing the order drops the newly arrived byte. */ int uart_poll_status(struct uart_port_ctx *ctx, int mode) { uint32_t status; if (!ctx || !ctx->sr_reg) return -1; status = *ctx->sr_reg; switch (mode) { case 0: if (status & UART_SR_OVERRUN) { *ctx->sr_reg = UART_SR_OVERRUN; ctx->rx_drops++; } __attribute__((fallthrough)); case 1: if (status & UART_SR_RXRDY) ctx->rx_frames++; break; default: return -2; } return (int)sizeof(*ctx); }- Function opening brace sits alone at column 1 while guard clauses keep the body at 1-2 tab stops.
- Aligned switch/case uses __attribute__((fallthrough)) so GCC -Wextra verifies intentional fallthrough.
checkpatch.pl / CodingStyle(7) GL-E00 Quick Reference checkpatch.pl / CodingStyle(7) SYNOPSIS ./scripts/checkpatch.pl --no-tree --strict -f driver_file.c gcc -std=c11 -Wall -Wextra -Wimplicit-fallthrough -Wmisleading-indentation -Werror -c file.c KEY RULES (Linux kernel Documentation/process/coding-style.rst) Tabs & Width Hard tab ('\t') = 8 columns; preferred limit 80 cols (100 cols max when readability wins). Braces Functions open '{' on column 1 of next line; if/for/while/switch/struct open '{' on same line. Multi-branch If any branch of if/else needs braces, place braces on EVERY branch of that construct. Operators Space after if/for/while/switch/return; NO space after sizeof/alignof/typeof or unary ! ~ ++ --. Comments Use /* ... */ block comments explaining invariants (why), never restating C syntax (how). Kernel Systems Academy Lesson 4.1 checkpatch.pl / CodingStyle(7) GL-E00 quick reference · full manual page: man 7 checkpatch.pl / CodingStyle Host C11 Style Scanner for Tabs, Stars, and Fallthroughs
Before running scripts/checkpatch.pl against a full driver tree, understanding how each lexical check works removes all mystery from build-gate failures. On our Linux host, we can write a compact ISO C11 style scanner (verify.c) that expands 8-column tab stops, measures visual line width and indentation depth, detects sizeof ( spacing and type* var star misplacement, and checks switch blocks for unannotated fallthrough.
This host verification binary runs in unprivileged user space under gcc -std=c11 -Wall -Wextra -Werror and proves exact lexical rule detection on representative C lines. Hardware register side effects cited in comments still require validation on ARMv7-A silicon.
learner@ksa:~/gl-e00/m04-l01$ bat -H 22 -H 35 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> struct line_metrics { int tab_depth; int visual_cols; bool leading_spaces; bool bad_sizeof_space; bool bad_type_star; }; static struct line_metrics scan_style_line(const char *line) { struct line_metrics m = {0, 0, false, false, false}; bool in_indent = true; for (size_t i = 0; line[i] != '\0' && line[i] != '\n'; i++) { char c = line[i]; if (in_indent && c == '\t') { m.tab_depth++; m.visual_cols += 8 - (m.visual_cols % 8); } else if (in_indent && c == ' ') { if (line[i + 1] != '*') m.leading_spaces = true; m.visual_cols++; } else { in_indent = false; m.visual_cols += (c == '\t') ? (8 - (m.visual_cols % 8)) : 1; } } if (strstr(line, "sizeof (") != NULL) m.bad_sizeof_space = true; if (strstr(line, "char* ") != NULL || strstr(line, "uint32_t* ") != NULL) m.bad_type_star = true; return m; } int main(void) { const char *clean = "\t\tstatus = sizeof(*ctx) + (*reg & 0xFFU);\n"; const char *flawed = " char* buf = alloc_pkt(sizeof (struct hdr));\n"; const char *deep = "\t\t\t\t\t*reg = 0x1U;\n"; struct line_metrics c = scan_style_line(clean); struct line_metrics f = scan_style_line(flawed); struct line_metrics d = scan_style_line(deep); if (c.tab_depth != 2 || c.leading_spaces || c.bad_sizeof_space || c.bad_type_star) return 1; if (!f.leading_spaces || !f.bad_sizeof_space || !f.bad_type_star) return 2; if (d.tab_depth <= 3 || d.visual_cols < 40) return 3; printf("CLEAN_LINE tabs=%d cols=%d violations=0\n", c.tab_depth, c.visual_cols); printf("FLAWED_LINE spaces=%d sizeof_sp=%d type_star=%d\n", f.leading_spaces ? 1 : 0, f.bad_sizeof_space ? 1 : 0, f.bad_type_star ? 1 : 0); printf("DEEP_NEST_ALARM tabs=%d visual_col_start=%d (>3 refactor!)\n", d.tab_depth, 5 * 8); return 0; }- Each leading hard tab advances visual_cols to the next 8-column boundary while counting nesting depth.
- Detects space-indented code (excluding block-comment '*'), 'sizeof (' spacing, and 'char* ' star traps.
Verifying Compiler Diagnostics and Tab-Stop Telemetry
Compiling verify.c under gcc -std=c11 -Wall -Wextra -Werror exercises GCC's built-in -Wmisleading-indentation and -Wimplicit-fallthrough passes directly on our scanner implementation. On execution, CLEAN_LINE confirms 2 hard tabs (16 visual columns plus expression width = 54 columns) with zero formatting violations.
Simultaneously, FLAWED_LINE flags leading-space indentation, sizeof ( spacing, and type-attached char* syntax in a single pass, while DEEP_NEST_ALARM demonstrates why 5 tab stops consume 40 columns before a single token of C logic is written.
learner@ksa:~/gl-e00/m04-l01gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m04-l01./verifyCLEAN_LINE tabs=2 cols=55 violations=0FLAWED_LINE spaces=1 sizeof_sp=1 type_star=1DEEP_NEST_ALARM tabs=5 visual_col_start=40 (>3 refactor!)learner@ksa:~/gl-e00/m04-l01learner@ksa:~/gl-e00/m04-l01strace -e trace=write,exit_group ./verifywrite(1, "CLEAN_LINE tabs=2 cols=55 violat"..., 142) = 142exit_group(0) = ?+++ exited with 0 +++Formatting Traps That Disguise Control-Flow and Type Bugs
Treat style conformance as a zero-noise baseline for code review. When indentation, braces, and operator spacing are 100% uniform, any visual asymmetry on screen immediately corresponds to a genuine semantic anomaly — such as an unbraced macro expansion, a missing break;, or an inverted error check.
Pair .editorconfig / .clang-format (UseTab: Always, IndentWidth: 8, TabWidth: 8) with compiler warning flags so formatting drift never reaches peer review.
Dangling Multi-Line Branch in Partially Braced if/else:
- Symptom: Adding a
pr_debug()trace line to anelseclause causes the subsequent operational statement to execute unconditionally on both true and false paths. - Root Cause: Leaving one branch of an
if/elseunbraced when the sibling branch spans multiple lines invites human edit errors thatGCConly catches if indentation happens to remain consistent. - Fix: Place K&R
{ ... }braces around every branch of anif/else if/elsechain whenever any single branch requires more than one line or statement.
Comma-Separated Pointer Declarator Star Misplacement:
- Symptom: Declaration
uint8_t* rx_buf, tx_buf;fails with invalid type conversion or truncates a32-bit buffer address into an8-bit byte when assigningtx_buf. - Root Cause: C grammar binds
*to the individual declarator (*rx_buf), not the base type (uint8_t), sotx_bufis silently allocated as a scalaruint8_t. - Fix: Always attach
*to the variable identifier (uint8_t *rx_buf, *tx_buf;) and prefer one initialized pointer declaration per line.
Guided Practice
Extend scan_style_line() in verify.c to flag lines whose expanded visual_cols exceed 80 characters unless the line contains a quoted diagnostic format string ("). Why does Linux kernel CodingStyle forbid splitting user-visible printk strings across multiple lines even when they exceed column 80?
Recompile with gcc -std=c11 -Wall -Wextra -Werror verify.c -o verify and test two inputs: a 92-column arithmetic expression (must flag over_80 = true) and a 92-column pr_err string literal (must pass so engineers can git grep exact dmesg error text).
Independent Practice
Write a multi-line scanner function check_switch_fallthrough(const char **lines, size_t n) that inspects consecutive lines inside a switch block and detects any case body that executes statements and reaches the next case or default label without break;, return, goto, or an explicit fallthrough annotation.
Verify your scanner against three synthetic switch blocks: a clean break;-terminated case, an empty stacked label (case 1: case 2:), and an unannotated non-empty fallthrough (must return exact offending line index with 0 compiler warnings).
Verification Checks
Key takeaways
- Linux kernel CodingStyle mandates 8-column hard tabs and an 80-to-100 column line budget so functions exceeding 3 indentation levels force helper extraction.
- Control statements place opening braces on the same K&R line while function definitions place opening braces at column 1, and switch/case labels align vertically with explicit fallthrough annotations.
- Pointer asterisks bind to the identifier (
char *buf) rather than the base type, while function-like operators (sizeof(struct file)) omit space before the opening parenthesis. - C89/C11 block comments (
/* ... */) document hardware timing, lock order, and ownership invariants (why) rather than restating C syntax mechanics (how).