Sign in Join
Wiki copytemporary

Inc and Dec: what changed

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

Title: Inc and Dec

OldNewLine
1+The [[Procedure|procedures]] `inc` and `dec` increment or decrement a given variable by default by one.
2+
3+## usage
4+
5+The first parameter specifies an ordinal value variable (e. g. an [[Integer|integer]] or enumeration type) and the second optional parameter may specify a different addend/subtrahend.
6+
7+``` pascal
8+program incDecDemo(input, output, stderr);
9+
10+type
11+ primaryColor = (red, green, blue);
12+
13+var
14+ phase: primaryColor;
15+ x: longint;
16+
17+begin
18+ // enumeration type
19+ phase := red;
20+ inc(phase); // phase becomes green
21+ writeLn(phase);
22+
23+ // integer
24+ x := 1;
25+ inc(x, -1); // x becomes zero
26+ writeLn(x);
27+
28+ x := 1;
29+ dec(x); // same as above: x becomes zero
30+ writeLn(x);
31+end.
32+```
33+
34+## background
35+
36+In [[FPC]]’s [[System unit|system unit]] the [`inc`](https://www.freepascal.org/docs-html/rtl/system/inc.html) and [`dec`](https://www.freepascal.org/docs-html/rtl/system/dec.html) procedures are compiler procedures. They exist in order to optimize for certain architectures where dedicated `inc` and `dec` [[Assembly language|assembler]] instructions are available.
37+
38+## special behaviors
39+
40+If `{$rangeChecks}` are turned on, those procedures may generate a run-time error (RTE 201). Also `{$overflowChecks}` may be generated (with a small difference in [[Mode TP|TP mode]]).
41+
42+If [[Pointer|pointer]] arithmetics are allowed by the `{$pointerMath}` compiler switch, `inc` and `dec` work on pointers, too.
43+
44+In the case of typed pointers, e. g. a pointer to a [[Record|record]], the target’s type size is considered automatically. For instance:
45+
46+``` pascal
47+program pointerIncDemo(input, output, stderr);
48+
49+{$pointerMath on}
50+
51+var
52+ p: PQWord;
53+
54+begin
55+ inc(p);
56+ inc(p, 3);
57+end.
58+```
59+
60+will generate (excerpt):
61+
62+``` asm
63+; [pointerIncDemo.pas]
64+; [8] begin
65+ leaq -8(%rsp),%rsp
66+.Lc3:
67+; Var p located in register rax
68+ call FPC_INITIALIZEUNITS
69+ movq $0,%rax
70+; [9] inc(p);
71+ addq $8,%rax
72+; [10] inc(p, 3);
73+ addq $24,%rax
74+; [11] end.
75+ call FPC_DO_EXIT
76+ leaq 8(%rsp),%rsp
77+ ret
78+```
79+
80+## see also
81+
82+- [`succ`](https://www.freepascal.org/docs-html/rtl/system/succ.html) and [`pred`](https://www.freepascal.org/docs-html/rtl/system/succ.html)
83+- [[For|for-loops]]
84+
85+---
86+*From the Free Pascal wiki, page "Inc and Dec", as it stood on 2022-08-10 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).*
87+Category: Pascal

Back to history