Cyclomatic Case switch statement complexity

I am confusing the CC switch statement

If I have the following code:

if (n >= 0) { switch(n) { case 0: case 1: printf("zero or one\n"); break; case 2: printf("two\n"); break; case 3: case 4: printf("three or four\n"); break; } } else { printf ("negative\n"); } 

What is CC?

I found a message , said that it is 5, with this diagram CC diagram

(ribs 17, not 16, I think it's a typo)

It says that we only need to count case 0 and case 1 as one

But I think the chart should be: CC diagram

Edges: 17,
Knots: 13,
17 - 13 + 2P = 6

I count all cases as 1

My professor OOSE said it is 6, but in a different way

He said:

 init => 1 if => 1 switch => 1 case 0 1 => 1 case 2 => 1 case 3 4 => 1 

therefore it should be 6

What is the correct answer?
I am very confused, thanks.


edited by :
Now I think he is 7 . yes 7
Because if n is greater than 5, it won’t do anything and exit the switch statement.

then we get this diagram:
enter image description here

now E = 18
18 - 13 + 2 = 7

Am I right ...?
really, really, really confused ...

+5
source share
2 answers

Ok, I found the answer.

from McCabe.com

http://www.mccabe.com/pdf/mccabe-nist235r.pdf

pages 26 and 27

The answer is 5 because the original CC version of McCabe considers the failed case to be 1.

+1
source

Code Metric Tools I worked with counting each case as a separate branch, even if it fails.

But this is an arbitrary choice. Code metric tools tend to fail with caution by default. How the switch statement will be ultimately evaluated is an internal implementation detail that will depend on the type of input and the number of cases (at least in C #).

The answer to reduce cyclic complexity caused by switch statements is to convert cases / outputs to a dictionary. In your example, this will be similar to the code example below. Keep in mind that this is for readability / maintainability only. If your switch statement is long enough, the .Net compiler will automatically convert it to a dictionary for you, so there is no performance increase.

 var outputs = new Dictionary<int, string>() { { 0, "zero or one\n" }, { 1, "zero or one\n" }, { 2, "two\n" }, { 3, "three or four\n" }, { 4, "three or four\n" } }; if (n >= 0) { printf(outputs[n]); } 
+2
source

All Articles