Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2023-06

Non-initialized member access warning

5 messages · 3 people · –

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Hairy Pixels

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

Steve Litt
to Hairy Pixels

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

Show quoted text 19 lines
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

Hairy Pixels
to Steve Litt
On Jun 8, 2023, at 12:58 AM, Steve Litt via fpc-pascal wrote: I know this isn't a very satisfying answer, but it's the best I can come up with.

Thanks but this is probably a question for the compiler devs. I'm curious if it's intended, a bug or not implemented. Seems like an obvious warning to have but maybe there's a reason...

Regards,
Ryan Joseph