Cyclomatic Complexity is a software quality metric used to indicate the number linearly independent paths in a function. This metric provides a measure of control complexity. As the number of control statements increases, the readability and maintainability of the code decreases. Do note, this is not a measure of data complexity. A long series of mathematical statements without any control statements will only have one path (i.e. a cyclomatic complexity of 1).
The example below looks like there are two paths, for a complexity of 2.
int add_saturate(short* result, int a, int b) { int overflow; long addtemp = a + b; if ((a > 0 && b > 0 && addtemp < 0) { overflow = 1; } else { overflow = 0; } *result = saturate(addtemp); return overflow; } |
However, the due to the Boolean operators of the first conditional, the complexity is actually 4. The expanded conditional is shown below.
int add_saturate(int* result, int a, int b) { int overflow; long addtemp = a + b; if (a > 0) { if (b > 0) { if (addtemp < 0) { overflow = 1; } else { overflow = 0; } } else { overflow = 0; } } else { overflow = 0; } *result = saturate(addtemp); return overflow; } |
This metric is useful for determining the number of tests that may need to be performed to fully test the system. Especially for safety-critical systems looking to achieve DO-178C certification, need to have tests that provide full statement coverage (level C), decision coverage (level B) and modified condition decision coverage (level A). Each control statement makes the program and testing more difficult to achieve full coverage.