Cyclomatic Complexity
Definition
Cyclomatic Complexity (CC), developed by Thomas McCabe (1976), is a quantitative measure of the number of linearly independent paths through a program's source code — based on its Control Flow Graph (CFG). It indicates the program's logical complexity and minimum number of test cases needed.
Formula
Given the Control Flow Graph:
V(G) = E − N + 2P
Where:
- E = number of edges in the CFG
- N = number of nodes in the CFG
- P = number of connected components (usually 1 for a single program)
Alternative Formula (using decision points)
V(G) = D + 1
Where D = number of decision points (if, while, for, case, etc.) in the program
Example
For code with:
if (x > 0) {
if (y > 0) {
print("Both positive");
}
}
- Decision points (D) = 2 (two
ifconditions) - V(G) = D + 1 = 3
What Cyclomatic Complexity Tells You
| CC Value | Risk Level |
|---|---|
| 1–10 | Simple, low risk |
| 11–20 | Moderate complexity, moderate risk |
| 21–50 | Complex, high risk |
| 50+ | Very high risk — untestable, needs redesign |
Significance
- Indicates the minimum number of independent test cases needed to achieve full branch coverage (this is exactly the basis for Path Testing, covered in Module 4)
- Higher CC = harder to understand, test, and maintain the code
- Widely used as a code quality/maintainability metric in static analysis tools (SonarQube, etc.)
Relationship to Testing
Cyclomatic Complexity directly determines the number of test paths needed for Path Testing (Basis Path Testing) — V(G) gives the minimum number of test cases to cover all independent paths.
Exam tip: Practice computing V(G) both ways — from a Control Flow Graph (E − N + 2) and from counting decision points (D + 1) — for a given code snippet or flowgraph. This is one of the most frequently asked numerical questions in the entire syllabus.