Search code examples
cyclomatic-complexity

Cyclomatic Complexity of switch case statement


I'm confusing about the CC of switch statement

If I have 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 the CC?

I found a post said that it's 5, with this diagram CC diagram

(the edges are 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 diagram should be: CC diagram

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

I count every cases as 1

My OOSE professor said it's 6, but in different way

He said:

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

so it should be 6

What's the correct answer?
I'm really confused, thanks.


edited:
Now I think it's 7. yes, 7
Because if n is more than 5, will just do nothing and exit the switch statement.

then we get this diagram:
enter image description here

now E = 18
18 - 13 + 2 = 7

am I correct..?
really, really, really confused...


Solution

  • Ok, I have found the answer.

    from McCabe.com, page 26 and 27

    The answer is 5, because the original version of CC by McCabe counts a fall-through case as 1.