Odd: what changed
Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.
| Old | New | Line | |
|---|---|---|---|
| 1 | 1 | The [[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]] | |
| 2 | 2 | ||
| 3 | 3 | ``` pascal | |
| 4 | 4 | abs(x) mod 2 = 1 | |
| 5 | 5 | ``` | |
| 6 | 6 | ||
| 7 | - | ||
| 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+}]]). | |
| 8 | 8 | ||
| 9 | 9 | ## application | |
| 10 | 10 | ||
| 11 | 11 | Beside 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]]: | |
| 12 | 12 | ||
| 13 | 13 | ``` pascal | |
| 14 | 14 | {$mode extendedPascal} | |
| 15 | 15 | program oddDemo(output); | |
| 16 | 16 | var | |
| 17 | 17 | i, sum: integer value 0; | |
| 18 | 18 | begin | |
| 19 | 19 | for i := 1 to 4 do | |
| 20 | 20 | begin | |
| 21 | 21 | { alternating scale factor 3^0, 3^1 based on Boolean } | |
| 22 | 22 | sum := sum + i * 3 pow ord(odd(i)); | |
| 23 | 23 | end; | |
| 24 | 24 | writeLn(sum); | |
| 25 | 25 | end. | |
| 26 | 26 | ``` | |
| 27 | 27 | ||
| 28 | - | ||
| 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. | |
| 29 | 29 | ||
| 30 | 30 | ## notes | |
| 31 | 31 | ||
| 32 | 32 | - There is no standard built‑in function “`even`”. Obviously the expression [[Not|not odd(x)]] determines whether an `integer` is even. | |
| 33 | 33 | - For constant expressions, `odd` can be evaluated at compile-time, thus it can appear in the [[Const|const section]]. | |
| 34 | 34 | - 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. | |
| 35 | 35 | ||
| 36 | 36 | --- | |
| 37 | 37 | *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).* |
