Hairy Pixels via fpc-pascal said on Wed, 7 Jun 2023 15:44:43 +0700

>I'm curious, why doesn't the following code give a warning? Shouldn't
>the compiler know you're assigning to "r" which hasn't been
>initialized yet?
>
>type
>       TMyClass = class
>               x: integer;
>       end;
>
>procedure MyProcedure; 
>var
>       r: TMyClass;
>begin
>       r.x := 1;
>end;
>
>
>Regards,
>       Ryan Joseph

If I had to guess, I'd say it's because you needed to and did declare
{$mode objfpc} or {$mode delphi}, which, my guess would be, don't warn
against using uninitialized variables. The following program contains
your code but includes r := tmyclass.create to allocate RAM to the
object. If that line is commented out, you get a runtime 216, which I
believe is a memory access violation.

================================================
{$mode objfpc}             {Needed for classes}
{$rangechecks on}          {Check for runtime memory tromp}
{$warnings on}             {List all warnings}
program junk3;
type
        TMyClass = class
                x: integer;
        end;

procedure show(c: tmyclass);
begin
        writeln(c.x);
end;

procedure MyProcedure; 
var
        r: TMyClass;
begin
        {Comment out following line to produce memory error}
        r := tmyclass.create; {Allocate ram for object r}
        r.x := 1;
        show(r);
end;

begin
myprocedure;
writeln('Finished');
end.
================================================

I explored {$warn whatever}, and none of the whatevers pertained to
uninitialized varibles, and {$warnings on} didn't bring out a warning.
I've seen uninitialized var warnings in other code, so by process of
elimination I'd imagine this is due to {$mode delphi} and its cousins,
which are necessary to recognize "class" as a reserved word.

I know this isn't a very satisfying answer, but it's the best I can
come up with.

SteveT

Steve Litt 
Autumn 2022 featured book: Thriving in Tough Times
http://www.troubleshooters.com/bookstore/thrive.htm
_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply via email to