Search code examples
pascalfreepascallazarus

Why does setting a Char variable to nil cause compilation to fail?


In my case below I don't want c to be assigned to anything until the first character of the file is read.

I tried setting the Char variable c to nil (c := nil;) but compilation fails. I tried an empty string like below, and still doesn't work.

It works when I set it to an empty space, but it seems peculiar that I have to do that.

Is there any way to initialize a Char to a null like value as you can do in other languages?

program CSVToMarkdown;
 
{$mode objfpc}{$H+}{$J-}

uses
    Sysutils;

var
    f: File of Char;
    c: Char;

begin
    Assign(f, 'test.csv');
    Reset(f);
    c := '';

    while not Eof(f) do
    begin
        Read(f, c);
        Write(c);
    end;

     Close(f);

    ReadLn;
end.

Solution

  • NIL is a value for pointers, or reference types (interfaces,class, dyn arrays) in general.

    Non reference types don't have a NIL value, the type char can take values from #0 to #255, and all are valid, though sometimes when interfacing to other languages #0 is interpreted as end of string.

    If you mean nullable types like in Java or .NET, there is no default support for them as they have the disadvantage of the type becoming larger than need be (iow becoming a pseudo record with added NULL boolean).

    There are some generics based solutions that try to implement nullable types, but I haven't used them, and they are not part of the standard distribution.