Sign in Join
Wiki copytemporary

Inc and Dec

The procedures inc and dec increment or decrement a given variable by default by one.

usage

The first parameter specifies an ordinal value variable (e. g. an integer or enumeration type) and the second optional parameter may specify a different addend/subtrahend.

pascal
program incDecDemo(input, output, stderr);

type
    primaryColor = (red, green, blue);

var
    phase: primaryColor;
    x: longint;

begin
    // enumeration type
    phase := red;
    inc(phase); // phase becomes green
    writeLn(phase);
    
    // integer
    x := 1;
    inc(x, -1); // x becomes zero
    writeLn(x);
    
    x := 1;
    dec(x); // same as above: x becomes zero
    writeLn(x);
end.

background

In FPC’s system unit the inc and dec procedures are compiler procedures. They exist in order to optimize for certain architectures where dedicated inc and dec assembler instructions are available.

special behaviors

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 TP mode).

If pointer arithmetics are allowed by the {$pointerMath} compiler switch, inc and dec work on pointers, too.

In the case of typed pointers, e. g. a pointer to a record, the target’s type size is considered automatically. For instance:

pascal
program pointerIncDemo(input, output, stderr);

{$pointerMath on}

var
    p: PQWord;

begin
    inc(p);
    inc(p, 3);
end.

will generate (excerpt):

asm
; [pointerIncDemo.pas]
; [8] begin
    leaq    -8(%rsp),%rsp
.Lc3:
; Var p located in register rax
    call    FPC_INITIALIZEUNITS
    movq    $0,%rax
; [9] inc(p);
    addq    $8,%rax
; [10] inc(p, 3);
    addq    $24,%rax
; [11] end.
    call    FPC_DO_EXIT
    leaq    8(%rsp),%rsp
    ret

see also


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.

Revision 1, last changed by WikiArchive .

Edited on wiki.freepascal.org by 3 people, 2015–2022

From the official wiki's backup of 26 May 2024: who edited this page there, and when. Edits made there after that date were not recorded, and the earlier versions are not shown here; the main page says why.

WhenWhoWhat changed
DjzepiCreated page
Kai BurghardtKai Burghardt moved page Inc to Inc and Dec: merge: deduplicate page contents (minor)
Kai Burghardtunify Inc and Dec
Kai Burghardtspecial behaviors: xlink Mode TP (minor)
Kai Burghardtbackground: wording (minor)
TrevFixed template loop; fixed typos; categorised page (minor)
Kai Burghardtresolve Category: Pages using deprecated enclose attributes (minor)

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.