Home Knowledge Base Cyclomatic Complexity

Cyclomatic Complexity is a software metric developed by Thomas McCabe in 1976 that counts the number of linearly independent execution paths through a function or method — computed as the number of binary decision points plus one, providing both a measure of testing difficulty (the minimum number of unit tests required for complete branch coverage) and a maintainability threshold that predicts defect probability and refactoring need.

What Is Cyclomatic Complexity?

McCabe defined complexity in terms of the control flow graph:

$$M = E - N + 2P$$

Where E = edges (decision branches), N = nodes (statements), P = connected components (typically 1 per function). The practical calculation for most languages:

Start at 1. Add 1 for each:

Example Calculation:

def process(x, items):       # Start: M = 1
    if x > 0:                # +1 → M = 2
        for item in items:   # +1 → M = 3
            if item.valid:   # +1 → M = 4
                process(item)
    elif x < 0:              # +1 → M = 5
        handle_negative(x)
    return x                 # No addition for return
# Final Cyclomatic Complexity: 5

Why Cyclomatic Complexity Matters

Industry Thresholds

ComplexityRisk LevelRecommendation
1 – 5LowIdeal — well-decomposed logic
6 – 10ModerateAcceptable — monitor growth
11 – 20HighRefactoring strongly recommended
21 – 50Very HighDifficult to test; must refactor
> 50ExtremeEffectively untestable; critical risk

Variant: Cognitive Complexity

SonarSource introduced Cognitive Complexity (2018) as a complement to Cyclomatic Complexity. The key difference: Cognitive Complexity penalizes nesting more heavily than sequential branching, better modeling actual human comprehension difficulty. if (a && b && c) has Cyclomatic Complexity 3 but Cognitive Complexity 1 — the multiple conditions are conceptually grouped. Nested if/for/if/for structures receive escalating penalties reflecting the exponential difficulty of tracking deeply nested state.

Tools

Cyclomatic Complexity is the mathematically precise measure of testing difficulty — the 1976 formulation that transformed "this function is too complex" from a subjective complaint into an objective, measurable threshold with direct implications for minimum test coverage requirements, defect probability, and code maintainability.

cyclomatic complexitycode ai

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.