Skip to main content

Command: Invert IF Statement

Function: This command inverts the IF statement without changing the semantics of the IF statement. The condition is negated. The statements in the THEN and ELSE branches are swapped. All comments are retained.

Call: Context menu under Refactoring command

Requirement: The cursor is positioned anywhere within an IF statement.

Table 2. Rules for negation

Expression

Negated Expression

Description

<

>=

The comparison on "less than" becomes "greater than" and vice versa.

<=

>

The comparison on "less than or equal to" becomes "greater than" and vice versa.

=

<>

The comparison on "equals" becomes "does not equal" and vice versa.

<expression1> AND <expression2>

( NOT <expression1> ) OR ( NOT <expression2> )

Negation according to De Morgan for AND operator

<expression1> OR <expression2>

(NOT <expression1> ) AND (NOT <expression2> )

Negation according to De Morgan for OR operator

<expression>

NOT <expression>

Standard negation

NOT <expression>

<expression>

No double NOT expression

a (*comment*) = b

a (*comment*) <> b

Comments are retained. This applies especially for swapped operands



Example 9. Example
PROGRAM Inversion1
VAR
    xA, xB, xC : BOOL;
    iVar : INT;
END_VAR
iVar := 0;
IF NOT(xA AND xB AND xC) THEN
	iVar:= 1; (* IF 1 *)
ELSE
	iVar := iVar + 1; (* ELSE counter*)
END_IFiVar := 0;

Code after calling the command with inverted logic with the same semantics:

 iVar := 0;
IF (xA AND xB AND xC) THEN
    iVar := iVar + 1; (* ELSE counter*)
ELSE
    iVar:= 1; (* IF 1 *)
END_IF