Delphi (actually Pascal) has the function Odd(x: integer): boolean which returns true, if the argument is not divisible by 2, false if it is:
if Odd(x) then
WriteLn('Argument is odd.')
else
WriteLn('Argument is even.')
Alternatively one could use the mod operator instead:
if (x mod 2) <> 0 then
WriteLn('Argument is odd.')
else
WriteLn('Argument is even.')
Is there any difference regarding the performance? I'd expect the compiler to generate optimized code for a system function.
I'm particularly interested in an answer regarding Delphi 2007 but if somebody can check other Delphi versions too that would be nice.
Odd is the best anyway;
As for x mod 2
check, the performance depends on whether x
is of signed or unsigned integer; the code generated for unsigned types is more effective.
Delphi XE compiler:
Odd(x):
Project11.dpr.10: if Odd(x) then
0040F327 F645FC01 test byte ptr [ebp-$04],$01
0040F32B 741B jz $0040f348
x mod 2, Unsigned x
(longword):
Project11.dpr.14: if (x mod 2) <> 0 then
0040F431 8B45FC mov eax,[ebp-$04]
0040F434 83E001 and eax,$01
0040F437 85C0 test eax,eax
0040F439 741B jz $0040f456
x mod 2, Signed x
(longint):
Project11.dpr.14: if (x mod 2) <> 0 then
0040F361 8B45FC mov eax,[ebp-$04]
0040F364 2501000080 and eax,$80000001
0040F369 7905 jns $0040f370
0040F36B 48 dec eax
0040F36C 83C8FE or eax,-$02
0040F36F 40 inc eax
0040F370 85C0 test eax,eax
0040F372 741B jz $0040f38f