SA0041: Possibly loop-invariant code

Function

Determines assignments in (FOR, WHILE, REPEAT) loops that calculate the same value for each loop pass. Such lines of code could be inserted outside the loop.

Reason

This is a performance warning. Code that is executed in a loop, but does the same thing in every loop pass, can be executed outside the loop.

Importance

Medium

Sample:

In the following sample SA0041 is output as error/warning, since the variables nTest1 and nTest2 are not used in the loop.

PROGRAM MAIN
VAR CONSTANT
    cMax      : INT := 3;
END_VAR
VAR
    nTest1    : INT := 5;
    nTest2    : INT := nTest1;
    nTest3    : INT;
    nTest4    : INT;
    nTest5    : INT;
    nTest6    : INT;
    nIndex    : INT;
    nCounter  : INT;
END_VAR
FOR nCounter := 1 TO 100 DO
    nTest3 := nTest1 + nTest2;   // => SA0041
    nTest4 := nTest3 + nCounter; // no loop-invariant code, because nTest3 and nCounter are used within loop
    nTest6 := nTest5;            // simple assignments are not regarded
END_FOR
 
FOR nIndex := 1 TO cMax-1 DO     // => SA0041 for "cMax-1"
    nCounter := nCounter + 1;
END_FOR