2

Let's assume that we have a code like this:

switch(y)
{
case 1: case 2: case 3:
    function();
    break;
case 4: case 5: case 6:
    function_2();
    break;
}

Can we get the CC value as 6+1 here? Why a value of 1 is added? If the CC value is considered as 7, is that the number of independent paths?

What if a fall through scenario is considered above? As only possible two unique paths are there, 2 +1 =3

Which of the above are correct or are the both of them correct?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Spark
  • 47
  • 5
  • 3
    There are three (distinct) paths through this switch, not two. – khelwood Aug 20 '16 at 15:02
  • 7th case is when `y` is neither 1, 2, 3, 4, 5 nor 6. – Raphaël Aug 20 '16 at 15:02
  • To try answering the question, I would say CC must be defined in terms of what the code is logically doing, not what the processor will actually do (and we don't even know what it will do most of the time). We don't care if the `2` is going to visit less cases of the `switch` because we definitely know that in the end it will reach the same state as the `3`. I have a strong preference for saying the CC is 3 here – Dici Aug 20 '16 at 15:08
  • @Raphaël cyclomatic complexity is not about runtime comparisons or evaluations. It's a metric that can be calculated statically (at compile-time) – Dici Aug 20 '16 at 15:15
  • Yeah, 3 seems to be correct.But if the given snippet is ran through a tool like RSM ,it outputs a value of 7 as the CC value. Maybe both the values are correct? – Spark Aug 20 '16 at 15:18
  • The tool is likely considering each `case` label, e.g., it's really falling through `case 4:` to `case 5:`. IMO not necessarily the most useful way of looking at it, but whatever. – Dave Newton Aug 20 '16 at 15:19
  • So its basically like, – Spark Feb 16 '17 at 02:23
  • Thanks for the explanation, but if the y=2, the code will skip case 1 and jump to case 2 and 3 right, so if we write the above same code with IF conditions, we will get a CC of 7. – Spark Feb 16 '17 at 03:12

1 Answers1

2

As we know, CC = P+1.

Here, P = number of predicate nodes (conditions) = 2

Number of conditions will be 2 because:

Case branch can cover several alternative values or ranges, such as Case 1, 2, 5 To 10. As they introduce no additional branches to decide on, they do not increase cyclomatic complexity either.

source: here

So, CC = 2+1 = 3

Shahid
  • 2,288
  • 1
  • 14
  • 24
  • Thanks for the explanation, but if the y=2, the code will skip case 1 and jump to case 2 and 3 right, so if we write the above same code with IF conditions, we will get a CC of 7. – Spark Feb 16 '17 at 03:06