Sign in Join
Wiki copytemporary

Inc and Dec

Sent here from 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 .

Talk about this page

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