How to compute the cyclomatic complexity?
Software Engineering
Computer Science Engineering
682
Knowledge
Cyclomatic complexity is a software metric used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program's source code.
It was developed by Thomas J. McCabe, Sr. in 1976. Cyclomatic complexity is computed using the control-flow graph of the program: the nodes of the graph correspond to indivisible groups of commands of a program, and a directed edge connects two nodes if the second command might be executed immediately after the first command.
To compute the cyclomatic complexity of a program, you can use the following formula:
Code snippet
V(G) = P + 1
Where:
A predicate node is a node in the control-flow graph where a decision is made. For example, an if statement or a while loop would have a predicate node.
Here is an example of how to compute the cyclomatic complexity of a simple program:
Code snippet
// This program prints the numbers from 1 to 10
int main() {
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
return 0;
}
The control-flow graph for this program would look like this:
Code snippet
Start
/ \
/ \
/ \
i = 1 i <= 10
/ \ / \
/ \ / \
/ \ / \
i++ printf("%d\n", i)
/ \
/ \
/ \
End End
There are 4 predicate nodes in this control-flow graph:
Therefore, the cyclomatic complexity of this program is 4 + 1 = 5.
Cyclomatic complexity is a useful metric for measuring the complexity of a program. It can be used to identify programs that are at risk of being difficult to understand, test, and maintain.
The cyclomatic complexity of a section of source code is the count of the number of linearly independent paths through the source code. For instance, if the source code contained no decision points such as IF statements or FOR loops, the complexity would be 1, since there is only a single path through the code.