Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Delphi record fields via . or ^

Tags:

delphi

I came across something in the Delphi language that I hadn't noticed before. Consider a simple record and a pointer to that record:

TRecord = record
     value : double;
end;
PTRecord = ^TRecord;

Now declare a variable of type PTRecord:

var x : PTRecord;

and create some space:

x := new (PTRecord);

I noticed that I can access the value field using both the '.' notation and the '^.' notation. Thus the following two lines appear to be operationally equivalent, the compiler doesn't complain and runtime works fine:

x.value := 4.5;
x^.value := 2.3;

I would have thought that '^.' is the correct and only way to access value? My question is, is it ok to use the simpler dot notation or will I run into trouble if I don't use the pointer indirection '^.'? Perhaps this is well known behavior but it's the first time I've come across it.

like image 895
rhody Avatar asked May 30 '13 19:05

rhody


3 Answers

It is perfectly sound and safe to omit the caret. Of course, logic demands the caret, but since the expression x.value doesn't have a meaningful intepretation in its own, the compiler will assume you actually mean x^.value. This feature is a part of the so-called 'extended syntax'. You can read about this at the documentation.

like image 65
Andreas Rejbrand Avatar answered Nov 19 '22 03:11

Andreas Rejbrand


When Extended syntax is in effect (the default), you can omit the caret when referencing pointers.

like image 35
ain Avatar answered Nov 19 '22 04:11

ain


Delphi has supported that syntax for close to two decades. When you use the . operator, the compiler will apply the ^ operator implicitly. Both styles are correct. There is no chance for your program doing the wrong thing since there is no case where presence or absence of the ^ will affect the interpretation of the subsequent . operator.

Although this behavior is controlled by the "extended syntax" option, nobody ever disables that option. You can safely rely on it being set in all contexts. It also controls availability of the implicit Result variable, and the way character pointers are compatible with array syntax.

like image 4
Rob Kennedy Avatar answered Nov 19 '22 02:11

Rob Kennedy