Skip to content
C++: Check nested brackets with a stack

C++: Check nested brackets with a stack

November 11, 2026

Equal counts of opening and closing brackets do not establish correct nesting. The string ([)] has matching counts but closes the wrong bracket first. A stack records the closing bracket expected next.

Prepare a scratch directory

Tested on Linux with GCC 14.2.0 in C++20 mode. You need Bash, a C++20 compiler and standard library, a text editor, and the mktemp, rm, and rmdir utilities. Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save as cpp-stack-check-nested-brackets.cpp:

#include <cassert>
#include <iostream>
#include <stack>
#include <string_view>

bool balanced(std::string_view text) {
    std::stack<char> expected;
    for (char ch : text) {
        switch (ch) {
        case '(': expected.push(')'); break;
        case '[': expected.push(']'); break;
        case '{': expected.push('}'); break;
        case ')': case ']': case '}':
            if (expected.empty() || expected.top() != ch) return false;
            expected.pop();
            break;
        default: break;
        }
    }
    return expected.empty();
}

int main() {
    assert(balanced(""));
    assert(balanced("a([b]{c})"));
    assert(!balanced("([)]"));
    assert(!balanced(")"));
    assert(!balanced("("));
    std::cout << std::boolalpha;
    for (std::string_view text : {"a([b]{c})", "([)]", ")", "("}) {
        std::cout << text << ": " << balanced(text) << '\n';
    }
}

Compile and run:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic cpp-stack-check-nested-brackets.cpp -o cpp-stack-check-nested-brackets &&
./cpp-stack-check-nested-brackets

Observed output:

a([b]{c}): true
([)]: false
): false
(: false

How it works

Each opening bracket pushes its expected closer. A closing bracket must match the most recently pushed value, which is the stack’s top. Short-circuit evaluation checks emptiness before accessing that top. pop removes the matched value and returns no element.

A mismatch can fail immediately, but success requires reaching the end with an empty stack. Otherwise the input still has unclosed brackets. Non-bracket characters are ignored by this deliberately small grammar.

Limits and choices

This is not a C++ source parser: brackets inside strings and comments still count. It is suitable for a format whose grammar treats every bracket as structural. Stack storage grows with nesting depth, so limit input size or nesting for external data. The algorithm scans characters once and uses storage proportional to maximum nesting. The example has no I/O beyond its fixed test strings and printed results.

The C++ working draft specifies the library operation used here. The example uses the C++20 interface tested above; newer draft additions are outside its scope.

Clean up

rm -- cpp-stack-check-nested-brackets.cpp cpp-stack-check-nested-brackets
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect the remaining files before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on