pointersdelphifreepascaldereference

In Delphi/Free Pascal: is ^ an operator or does it simply denote a pointer type?


In Delphi/Free Pascal: is ^ an operator or does it simply denote a pointer type?

program Project1;

{$APPTYPE CONSOLE}

var
    P: ^Integer;

begin
    New(P);

    P^ := 20;
    writeln(P^); // How do I read this statement aloud? P is a pointer?

    Dispose(P);

    readln;
end.

Solution

  • When ^ is used as part of a type (typically in a type or variable declaration) it means "pointer to".

    Example:

    type
      PInteger = ^Integer;
    

    When ^ is used as a unary postfix operator, it means "dereference that pointer". So in this case it means "Print what P points to" or "Print the target of P".

    Example:

    var
      i: integer; 
      a: integer;     
      Pi: PInteger;
    begin
      i:= 100;
      Pi:= @i;  <<--- Fill pointer to i with the address of i
      a:= Pi^;  <<--- Complicated way of writing (a:= i)
                <<--- Read: Let A be what the pointer_to_i points to
      Pi^:= 200;<<--- Complicated way of writing (i:= 200)
      writeln('i = '+IntToStr(i)+' and a = '+IntToStr(a));