From Free Pascal wiki
Jump to navigationJump to search

Deutsch (de) English (en) polski (pl)

The standard function odd returns true if and only if the passed integer parameter is odd, that means it is not divisible by 2. Odd(x) is by definition equivalent to the expression

abs(x) mod 2 = 1

The abs serves the purpose of any potential for confusion regarding the sign of the mod operator in conjunction with a negative operand. It is unnecessary in a fully-ISO‑compliant compiler (for FPC this means {$modeSwitch ISOMod+}).


Beside using odd directly, in combination with ord it can be useful to simplify calculations. The following program calculates [math]\displaystyle{ 1 \cdot 3^1 + 2 \cdot 3^0 + 3 \cdot 3^1 + 4 \cdot 3^0 }[/math] (= [math]\displaystyle{ 3 + 2 + 9 + 4 }[/math]) without the need of branches:

{$mode extendedPascal}
program oddDemo(output);
	i, sum: integer value 0;
	for i := 1 to 4 do
		{ alternating scale factor 3^0, 3^1 based on Boolean }
		sum := sum + i * 3 pow ord(odd(i));

NB: Despite {$mode extendedPascal} the shown integer power operator pow and initial-value specification are not yet supported by FPC as of version 3.2.0.


  • There is no standard built‑in function “even”. Obviously the expression not odd(x) determines whether an integer is even.
  • For constant expressions, odd can be evaluated at compile-time, thus it can appear in the const section.
  • On most architectures odd can be implemented as a simple and x, 1, that is by masking the least-significant bit in a value. For these platforms, using type helpers from the sysUtils unit, x.testBit(0) has the same return value.