HomeToolsFormattingC/C++ Code Formatter

C/C++ Code Formatter

Beautify C and C++ source code files matching structural code specifications.

Formatting
Raw Code
Formatted Code

Formatting C and C++ starts with structure

Brace placement and indentation are not merely cosmetic when developers are reviewing unfamiliar systems code. A clear block shape helps reveal an early return, a loop nested under the wrong condition, or a lifetime boundary hidden in a dense function. The C/C++ Code Formatter offers a side-by-side workspace for applying two- or four-space indentation to line-oriented input.

Its scope is intentionally modest. Each non-empty line is trimmed and emitted at a tracked indentation level. A line beginning with } reduces that level; a line ending with { increases it. Square-bracket and tag-like conditions are also shared by the generic line formatter. It does not tokenize C, preprocess headers, parse templates, split statements, or choose a named style. That distinction determines what source it can improve safely.

Source shape matters more than source size

The formatter works best when braces already occupy useful line boundaries:

int classify(int value) {
if (value < 0) {
return -1;
}
return value == 0 ? 0 : 1;
}

With four spaces selected, brace depth becomes visible:

int classify(int value) {
    if (value < 0) {
        return -1;
    }
    return value == 0 ? 0 : 1;
}

By contrast, this one-line program remains one line because the formatter does not split at braces or semicolons:

int main(){puts("ready");return 0;}

Choosing an indentation width cannot create structural line breaks that are absent from the input. If you need full C beautification or C++ pretty printing, use clang-format or another parser-aware formatter that can identify tokens within a physical line.

Understand the two controls

The Raw Code pane accepts plain text. The 2 Spaces and 4 Spaces selector determines how many literal spaces represent each detected nesting level. Four spaces is common in many C projects; two is frequent in projects that prioritize narrow lines or follow a particular upstream convention. Neither choice is universally correct. Repository files such as .clang-format, contribution guides, and surrounding source are stronger signals.

Formatted Code is read-only and refreshes as you edit. The Copy button writes its contents to the clipboard and briefly confirms completion. There is no download button, parser error display, language-version selector, tab option, or brace-style selector. Existing opening braces are not moved between same-line and Allman style positions.

Empty lines are dropped. Leading and trailing whitespace on every retained line is removed before indentation is reapplied. This behavior can clean obvious left-margin inconsistencies, but it also erases intentional vertical separation and alignment.

A disciplined scratchpad workflow

Use this C/C++ formatter on a duplicate snippet, not the only copy of a source file. First place braces on meaningful lines in your editor if the input is compressed. Paste one function or small declaration region. Select the project’s indentation width, then compare input and output line by line.

Pay special attention to preprocessor directives, continued macros, comments, string literals, initializer lists, switch labels, namespaces, classes, lambdas, and templates. Copy only after confirming those constructs. Apply the snippet to the source through a normal diff so whitespace changes remain reviewable.

Then run the project’s canonical formatter if it has one. Compile with the exact C or C++ standard, warning flags, feature macros, include paths, and platform toolchain used by the project. Execute tests and sanitizers appropriate to the change. A formatting preview can expose structure to a person, but only the compiler and build system can interpret the full translation unit.

For a broad formatting migration, configure clang-format, pin its version, format a dedicated commit, and prevent unrelated semantic edits from being mixed into that diff. Large style changes are much easier to review when mechanical and functional changes remain separate.

Preprocessor and macro hazards

The C preprocessor transforms source before the compiler parses it. A multiline macro uses a trailing backslash to continue its replacement list, and spaces after that backslash can break continuation. Trimming may remove harmless spaces, but a line-oriented formatter cannot understand the macro as a unit or preserve deliberate alignment.

Conditional compilation can make braces appear unbalanced in raw source even though each active configuration is valid:

#if FEATURE_ENABLED
if (ready) {
#endif
    run();
#if FEATURE_ENABLED
}
#endif

Tracking visible brace endings without evaluating macros can produce misleading indentation. Likewise, macro arguments may contain commas or brace-like tokens whose role becomes clear only after expansion. Keep preprocessor-heavy regions under project tooling and test multiple build configurations.

Directives conventionally begin at column zero. Because the formatter emits every line at its current tracked level, a directive inside a detected brace region may be indented. Some compilers permit leading whitespace before #, but repository style or external tooling may require a different presentation.

C++ makes lightweight formatting harder

C++ braces can introduce function bodies, classes, namespaces, lambdas, initializer lists, aggregate values, and requires expressions. A formatter needs token and grammar context to distinguish these and decide line breaks. Templates introduce angle brackets that can also mean comparisons. Attributes, concepts, modules, designated initializers, raw strings, and operator overloads add further cases.

Raw string literals may contain arbitrary lines, braces, and indentation that are part of the literal. Trimming those lines can change program output. Ordinary multiline comments and embedded code examples can also rely on alignment. Never pass a region containing literal payloads through this tool without verifying exact contents.

Labels and case clauses often follow style-specific indentation that is not equivalent to brace depth. Access specifiers such as public: may be outdented relative to members. Constructor initializer lists and chained calls use continuation indentation rather than a new brace level. This component does not model any of those conventions.

Choosing a real project formatter

clang-format supports C, C++, Objective-C, and related languages, with built-in style families and granular configuration. A checked-in .clang-format makes results repeatable across editors and CI. Uncrustify and Artistic Style serve projects with different requirements. IDE formatters can be effective when their settings are shared rather than held in one developer’s profile.

Select tooling based on language versions, existing style, macro support, and adoption in the build environment. Format only supported directories, and exclude generated or vendored code. Pinning the tool version avoids broad diffs when formatting algorithms evolve.

Formatting is not static analysis. clang-tidy, compiler warnings, sanitizers, and dedicated analyzers find classes of defects that indentation cannot. Conversely, a warning fix should not be hidden inside a repository-wide style rewrite.

Predict brace-depth changes before copying

Only braces at specific line positions affect the tracked level. A trimmed line beginning with } is emitted one level shallower; a line ending with { increases indentation for later lines. A closing brace after a statement and an opening brace followed by a comment do not trigger those exact checks. This explains why superficially similar styles can produce different output. Scan the first and last non-whitespace character of each line before using the result. If either brace position is obscured by another token, restructure the snippet in an editor or use clang-format rather than manually correcting a cascading indentation error.

Troubleshooting by symptom

Compressed statements stay compressed. The formatter processes whole lines and does not split on {, }, or ;. Add line breaks manually or use clang-format.

Preprocessor directives moved right. Output follows the current brace-derived level. Restore column-zero directives if required and avoid this formatter for conditional regions.

Blank lines between functions vanished. Empty input lines are skipped. Reintroduce intentional separation or use a formatter that retains style-aware vertical spacing.

A closing brace did not dedent. Dedenting requires the trimmed line to start with }. A brace following another token on the same physical line will not lower the level first.

A raw string or comment changed. Restore it from the original. The tool has no lexical awareness and trims every retained line.

C/C++ Code Formatter FAQ

Does it support both C and C++?

It accepts either as text, and simple brace-per-line blocks can be indented. It does not parse either language or implement C++-specific layout rules.

Can it convert K&R braces to Allman style?

No. Opening braces are not moved. Use a configurable syntax-aware formatter for brace-style conversion.

Does formatted output guarantee successful compilation?

No. The tool reports no syntax, type, preprocessing, linking, or undefined-behavior diagnostics. Compile and test the result.

Are tabs available?

No. The current selector emits two or four spaces only.

Why not paste a minified C file?

Without existing line breaks, the component has no opportunity to indent internal statements. A lexical formatter is required to split tokens safely.

What should be excluded from bulk formatting?

Generated files, third-party code, intentionally aligned tables, sensitive macro definitions, and literal payloads should follow repository policy. Exclude them through the canonical tool configuration rather than fixing each result manually.

Learn More

Read our comprehensive guide to master this utility.

Read Guide →