Cognitive Complexity is one of the source-code metrics Understand computes across 17+ languages — browse them in the GUI, export and track them, or script them with the Python API.
Cognitive Complexity
API ID: CognitiveComplexityLanguages: C, C++
Targets: Functions
Sonar's Cognitive Complexity Metric
Cyclomatic complexity counts the number of decision points. It relates to the number of paths and therefore to how hard code is to test. In contrast, the goal of Cognitive complexity is to capture how hard code is to understand. See https://www.sonarsource.com/resources/cognitive-complexity/ ↗ for the full description of the metric.
The documentation uses two code samples to show the difference between Cyclomatic and Cognitive complexities:
int sumOfPrimes(int max) // Cyclomatic Cognitive
{
int total = 0;
OUT: for (int i = 1; i <= max; ++i) { // `for` + 1 `for` + 1
for (int j = 2; j < i; ++j) { // `for` + 1 `for` + 1, nesting + 1
if (i %j == 0) // `if` + 1 `if` + 1, nesting + 2
goto OUT; // `goto` + 1
}
total += i;
}
return total; // Totals:
} // 3 + 1 = 4 Cognitive = 7
char* getWords(int number) { // Cyclomatic Cognitive
switch (number) { // `switch` + 1
case 1: // `case` + 1
return "one";
case 2: // `case` + 1
return "a couple";
case 3: // `case` + 1
return "a few";
default:
return "lots"; // Totals:
} // 3 + 1 = 4 Cognitive = 1
}
See also the blog article ↗ describing how the plugin is implemented.