Sign in Join
Wiki copytemporary

Mod: what changed

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

OldNewLine
11Back to [[Reserved words]].
22
33Mod (**mod**ulus) divides two numbers and returns only the remainder. For instance, the expression "a:= 13 mod 4;" would evaluate to 1 (a=1), while "b := 12 mod 4;" would evaluate to 0 (b=0).
44
55From the [language reference](http://freepascal.org/docs-html/current/ref/refsu45.html#x148-17000012.8.1):
66
77
88"The sign of the result of a Mod operator is the same as the sign of the left side operand of the Mod operator. In fact, the Mod operator is equivalent to the following operation :"
99
10-` I mod J = I - (I div J) * J`
10+```text
11+ I mod J = I - (I div J) * J
12+```
1113
1214For example "c:= -13 mod 4;" results in c = -1 and "c:= 10 mod -3;" results in c = 1.
1315
1416This is also what most other languages like C++ and Java do (see note)
1517
1618From version 3.1.1 FreePascal also supports the mod operator for floating point values when you include the math unit.\
1719The precision used is the highest precision available for the platform. for instance, the expression "a:= 12.9 mod 2.2;" would evaluate to 1.9. This is equivalent to I mod J = I - int(I / J) * J.
1820
1921The result is the same as the fmod function for the highest precision available for the platform.
2022
2123In older versions of FPC that support operator overloading you can add this feature yourself. Here's an example for double precision modulo.
2224
2325``` pascal
2426operator mod(const a, b: double) c: double; inline;
2527begin
2628 c:= a - b * Int(a / b);
2729end;
2830```
2931
3032## Note regarding Delphi compatibility
3133
3234Delphi conforms to ISO 7185 Pascal instead of the de facto standard. This ISO standard states:
3335
3436
3537Evaluation of a term of the form x mod y is an error if y is less than or equal to zero; otherwise there is an integer k such that x mod y satisfies the following relation:
3638
37-` 0 <= x mod y = x - k * y < y.`
39+```text
40+ 0 <= x mod y = x - k * y < y.
41+```
3842
3943That means that in Delphi "c:= 10 mod -3;" results in an error and an exception will be thrown at run-time.
4044
4145---
4246*From the Free Pascal wiki, page "Mod", as it stood on 2020-02-20 after a change by Trev, 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