McCabe's cyclomatic complexity

2019-07-19 06:20发布

问题:

To calculate the cyclomatic complexity of a code, I drew a control flow chart consisting of nodes and edges which helped me to calculate V (G) = E - N + 2 In my case E = 15 and N = 11. Resulting in a cyclomativ complexity of 6.

Now to confirm my answer I would like some help on finding linearly independent paths for the code blow:

int maxValue = m[0][0];         
for (int i = 0; i < N; i++)         
{                       
   for (int j = 0; j < N; j++)          
   {                        
      if ( m[i][j] > maxValue )         
      {                     
         maxValue = m[i][j];            
      }                     
   }                        
}                   
cout << maxValue << endl;           
int sum = 0;                    
for (int i = 0; i < N; i++)         
{                       
   for (int j = 0; j < N; j++)          
   {                        
      sum = sum + m[i][j];          
   }                        
}                           
cout << sum << endl;  

This should equal the result for my V (G), otherwise my calculation is wrong. Thank you for your help.

回答1:

McCabe's cyclomatic complexity gives an upper bound. Consider the following:

void func (const bool do_special) {
    if (do_special) {
        do_something_special_at_the_start();
    }

    always_do_this_stuff_in_the_middle();

    if (do_special) {
        do_something_special_at_the_end();
}

From a graph theory perspective, this has a cyclomatic complexity of three. However, since do_special is constant, there are only two independent paths through the code. The graph theory model doesn't know that some paths are impossible. The number of possible paths through the graph is sometimes less than the cyclomatic complexity.



回答2:

Hammen, A very good example for stating that this metric gives the upper bound. But somehow, you might have missed a point about the complexity of this example while giving it as three. Since you have shown do_something_...(), they are function calls. Hence in this case P = 3 and so the Cyclomatic complexity will be given by V(G) = E - N - 2*P, also E and N should include the edges and nodes of the called functions too. I think instead, the example can be written as:

void func (const bool do_special) {

   if (do_special) {
      /* do something at start */
   }
   :
   /* do something at middle */
   :
   if (do_speical) {
      /* do something at end */
   }
}

Hope you agree!