主要内容

Cyclomatic Complexity

Number of linearly independent paths in function body

Since R2023b

Description

Cyclomatic complexity measures the number of linearly independent paths in a function body. A high cyclomatic complexity indicates that the function has many linearly independent paths and requires a high number of test cases to evaluate the paths. To reduce the cyclomatic complexity of your code, consider refactoring the complex functions.

Polyspace Implementation

Polyspace® evaluates the cyclomatic complexity of a function as:

c=1N(on1)

Where:

  • N is the number of conditions in the code.

  • on is the number of outcomes for the nth decision point.

Polyspace adds 1 to the number of linearly independent paths for each function. For instance, consider this function:

void evalNum(int x)
{
  if (x > 0)                          // decision #1
    printf( "x is positive" );
  else if (x < 0)                     // decision #2
    printf( "x is negative" );
  else
    printf( "x is 0" );
}
Here:

  • N = 2

  • o1 = 2

  • o2 = 2

  • Number of function = 1

Then, the cyclomatic complexity is c = (2-1) + (2-1) + 1 = 3, indicating that the code snippet has three linearly independent paths.

Examples

expand all

In the function foo(), there are nine Boolean conditions, resulting in a cyclomatic complexity of 10. Testing this function requires testing 10 independent code paths, possibly with as many test cases. To ease testing, reduce the cyclomatic complexity per function.

int foo(int x,int y) 
{
	int flag;
	if (x <= 0){
		if (x > 10 ) { return 0; }
	}
	if (x<-240) {
		if (x < -2565) { 
			return (x < -253 ? 0: (x <22566 ? 1: (x < -25103 ? 0: 6))); 
		}
	}
	for (int i = 0; i< 10; i++)
	{
		while (x < y ) {flag = 1;++x;};
		flag = 0;
	}
	return flag;
}
Correction — Refactor Function

Split the function into two functions.

int foo2(int x,int y)
{
	
	if (x <= 0){
		if (x > 10 ) { return 0; }
	}
	if (x<-240) {
		if (x < -2565) { 
			return (x < -253 ? 0:  (x <22566 ? 1: (x < -25103 ? 0: 6))); 
		}
	}
}

int bar(int x,int y){
	int flag;
	for (int i = 0; i< 10; i++)
	{
		while (x < y ) {flag = 1; ++x;}
		flag = 0;
	}
	return flag;
}

The functions foo2 and bar have a lower cyclomatic complexity and are easier to test compared to foo.

Version History

Introduced in R2023b