Sign in Join
Wiki copytemporary

Odd: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11The [[Basic Pascal Tutorial/Chapter 1/Standard Functions|standard function]] [**`odd`**](https://www.freepascal.org/docs-html/rtl/system/odd.html) returns [[True|true]] if and only if the passed [[Integer|integer]] parameter is odd, that means it is not divisible by `2`. `Odd(x)` is by definition equivalent to the [[expression]]
22
33``` pascal
44abs(x) mod 2 = 1
55```
66
7-<small> The `abs` serves the purpose of any potential for confusion regarding the sign of the [[Mod|mod operator]] in conjunction with a *negative* operand. It is *unnecessary* in a *fully-ISO‑compliant* compiler (for [[FPC]] this means [[modeswitch|{$modeSwitch ISOMod+}]]). </small>
7+The `abs` serves the purpose of any potential for confusion regarding the sign of the [[Mod|mod operator]] in conjunction with a *negative* operand. It is *unnecessary* in a *fully-ISO‑compliant* compiler (for [[FPC]] this means [[modeswitch|{$modeSwitch ISOMod+}]]).
88
99## application
1010
1111Beside using `odd` directly, in combination with [[Ord|ord]] it can be useful to simplify calculations. The following [[Program|program]] calculates $`1 \cdot 3^1 + 2 \cdot 3^0 + 3 \cdot 3^1 + 4 \cdot 3^0`$ (= $`3 + 2 + 9 + 4`$) without the need of [[Branch|branches]]:
1212
1313``` pascal
1414{$mode extendedPascal}
1515program oddDemo(output);
1616var
1717 i, sum: integer value 0;
1818begin
1919 for i := 1 to 4 do
2020 begin
2121 { alternating scale factor 3^0, 3^1 based on Boolean }
2222 sum := sum + i * 3 pow ord(odd(i));
2323 end;
2424 writeLn(sum);
2525end.
2626```
2727
28-<small> NB: Despite [[Mode extendedpascal|{$mode extendedPascal}]] the shown `integer` power operator `pow` and initial-value specification are not yet supported by FPC as of version 3.2.0. </small>
28+NB: Despite [[Mode extendedpascal|{$mode extendedPascal}]] the shown `integer` power operator `pow` and initial-value specification are not yet supported by FPC as of version 3.2.0.
2929
3030## notes
3131
3232- There is no standard built‑in function “`even`”. Obviously the expression [[Not|not odd(x)]] determines whether an `integer` is even.
3333- For constant expressions, `odd` can be evaluated at compile-time, thus it can appear in the [[Const|const section]].
3434- 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 Helper|type helpers]] from the [[sysutils|sysUtils unit]], `x.testBit(0)` has the same return value.
3535
3636---
3737*From the Free Pascal wiki, page "Odd", as it stood on 2023-01-25 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history