cyclomatic-complexity

Cyclomatic complexity of a for loop


I've been introduced to the cyclomatic complexity with two different definitions. First "the cyclomatic complexity is the number of independent paths in the flux diagram of the code" and second "the number of times you have to run the program through different paths to have executed every part of it".

However, I have a problem with a for loop where both definitions aren't compatible.

In a for loop, the cyclomatic complexity through the first definition is two. However, you'd only have to run the loop once to go trough every part of the program.

So my question is, is the for a special case or is one of the definitions wrong?

Edit:

I´ve been told that the for loop checks for the condition and it could be that it wont even go inside the loop but I had the intuition that the graph in the for loop exited 'from the bottom' so which of these two graphs would be the one?

enter image description here


Solution

  • You have assumed that the for loop will always execute its enclosed contents in the loop body - that is not guaranteed if the for loop termination condition is already met on entry.

    There are two potential paths for that initial conditional branch as far as CCI is concerned: the normal one where the for loop contents do get executed at least once, and another where they do not.

    They are quite distinct paths through the for loop code and both need testing (unless you can be sure that skipping of the for loop body execution can never occur in your particular program).

    When the body of a for loop is not executed it could leave a variable uninitialised that has consequences later.