Metric: Cyclomatic Complexity

User Description

The Cyclomatic Complexity metric is used to measure the complexity of a program by counting the number of linearly independent paths in the source code.

Metric Calculation

Cyclomatic Complexity is computed using the control flow graph of the program. The complexity depends on the condition and decision points of the control flow graph.

For example:

  • No condition or decision point: Complexity = 1 (one path through the code).

  • One IF statement: Complexity = 2 (two paths through the code).

  • One IF statement with two conditions: Complexity = 3 (three paths through the code).

There are different interpretations/implementation of Cyclomatic Complexity, depending on the analysis tool. Some tools do not consider expressions with AND/OR/etc. in IF, REPEAT, WHILE, etc. statements. The McCabe Cyclomatic Complexity is always increased by +1. Other tools also consider the expressions in the code flow (outside an IF, REPEAT, etc. statement) but later used in an IF or REPEAT statement which results in a higher Cyclomatic Complexity result. The Cyclomatic Complexity implementation in EcoStruxure Machine Expert considers expressions with AND/OR/etc. but does not consider pre-calculated expressions in the code flow or specified in a method call.

Example

Cyclomatic Complexity calculation example:

// MCC +1 (Initial Value)

// MCC +0 (Pre calculation of condition not considered)
a := b OR c;

// MCC +0 (Method call with condition not considered in calling implementation)
METH4(a);

IF a AND b OR c XOR d AND NOT e THEN

   // MCC +5 (IF with 5 conditions)

    CASE i OF
       1..4:
           // MCC +1 (CASE range is considered as one condition)

           FOR i := 1 TO 10 DO               // MCC +1

               METH1();
           END_FOR

       10, 11, 12, 13:
           // MCC +1 (multiple CASE labels considered as one condition)

           REPEAT
               // MCC +1 (one condition in REPEAT)

               WHILE (a = TRUE AND b = FALSE) DO
                   // MCC +2 (two conditions in WHILE)

                   METH2();

               END_WHILE

           UNTIL (TRUE) END_REPEAT

        ELSE
            // MCC +0 (Default path through CASE statement)

            METH3();
    END_CASE
END_IF

Cyclomatic Complexity Result

Cyclomatic Complexity (MCC) = 12