Sign in Join

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

Mailing lists / fpc-pascal / 2023-05

Make a distinct pointer type

6 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

What's the best way to make a pointer type which is distinct so that the following snippet would give an error. I thought "type pointer" would do it but it doesn't seem to work.

type
  PA = type pointer;
  PB = type pointer;
var
  a: PA;
  b: PB;
begin
  a := b; // should give an error!
end;

Regards,
Ryan Joseph

Reply by email

Michael Van Canneyt
to Hairy Pixels
Hairy Pixels wrote 12 lines
What's the best way to make a pointer type which is distinct so that the following snippet would give an error. I thought "type pointer" would do it but it doesn't seem to work. type PA = type pointer; PB = type pointer; var a: PA; b: PB; begin a := b; // should give an error! end;

Type aliases are always assignment compatible.

As far as I know, there is no way to do what you want with just 'pointer'.

This will give an error:

Type
   RA = record end;
   RB = record end;
   PA = ^RA;
   PB = ^RB;
var
   a: PA;
   b: PB;
begin
   a := b;
end.

Michael.

Reply by email

Hairy Pixels
to Michael Van Canneyt

I'm trying to make an "opaque pointer" type for a c library so the types are just pointers but they should be incompatible. I guess I'll have to make all the records.

Show quoted text 14 lines
On May 31, 2023, at 9:20 PM, Michael Van Canneyt via fpc-pascal wrote: Type aliases are always assignment compatible. As far as I know, there is no way to do what you want with just 'pointer'. This will give an error: Type RA = record end; RB = record end; PA = ^RA; PB = ^RB;

Regards,
Ryan Joseph

Reply by email

Sven Barth
to Hairy Pixels

Hairy Pixels via fpc-pascal schrieb am
Do., 1. Juni 2023, 03:16:

Show quoted text 10 lines
> On May 31, 2023, at 9:20 PM, Michael Van Canneyt via fpc-pascal < > wrote: > > Type aliases are always assignment compatible. btw, what does the "type" prefix do then? I thought that made them non-aliases or distinct types.

It only makes a difference for the RTTI as well as overloading.

Regards,
Sven

Reply by email

Hairy Pixels
to Sven Barth

I just noticed this still doesn't provide good type safety as MyPtr can be assigned an untyped pointer. Are pointers simply not an option here? Maybe we need classes for opaque pointer types instead?

type
  _MyPtr = record end;
  MyPtr = ^_MyPtr;
var
  p: Pointer;
  x: MyPtr;
begin
  x := p; // Should be an error!
end;

Regards,
Ryan Joseph

Reply by email