Overflow/underflow in the data type Permalink

The CODESYS compiler generates code for the target device and computes temporary results always with the native size that is defined by the target device. For example, computation is performed at least with 32-bit temporary values on x86 and ARM systems and always with 64-bit temporary values on x64 systems. This provides considerable advantages in the computation speed and often also produces the desired result. But this also means that an overflow or underflow in the data type is not truncated in some cases.

Examples

Example 1

The result of this addition is not truncated and the result in ‎dwVar‎ is ‎65536‎.

VAR
wVar : WORD;
dwVar: DWORD;
END_VAR

wVar := 65535;
dwVar := wVar + 1;

Example 2

The overflow and underflow in the data type is not truncated and the results (‎bVar1, bVar2‎) of both comparisons are ‎FALSE‎ on 32-bit and 64-bit hardware.

VAR
wVar1 : WORD;
wVar2 : WORD;
bVar1 : BOOL;
bVar2 : BOOL;
END_VAR

wVar1 := 65535;
wVar2 := 0;
bVar1 := (wVar1 + 1) = wVar2;
bVar2 := (wVar2 - 1) = wVar1;

Example 3

By the assignment to ‎wVar3‎, the value is truncated to the target data type ‎WORD‎ and the result ‎bvar1‎ is ‎TRUE‎.

VAR
wVar1 : WORD;
wVar2 : WORD;
wVar3 : WORD;
bVar1 : BOOL;
END_VAR

wVar1 := 65535;
wVar2 := 0;
wVar3 := (wVar1 + 1);
bVar1 := wVar3 = wVar2;

Example 4

In order to force the compiler to truncate the temporary results, a conversion can be inserted.

The type conversion makes sure that both comparisons are 16-bit only and the results (‎bVar1, bVar2‎) of both comparisons are each ‎TRUE‎.

VAR
wVar1 : WORD;
wVar2 : WORD;
bVar1 : BOOL;
bVar2 : BOOL;
END_VAR

wVar1 := 65535;
wVar2 := 0;
bVar1 := TO_WORD(wVar1 + 1) = wVar2;
bVar2 := TO_WORD(wVar2 - 1) = wVar1;