Access to Delphi fields for writing through. or ^

I met something in Delphi that I had not noticed before. Consider a simple entry and a pointer to this entry:

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 how. designation and "^". notation. Thus, the following two lines seem to be functionally equivalent, the compiler does not complain, and the runtime works fine:

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

I would have thought that "^". is the correct and only way to access the value? My question is, is it good to use simpler dot notation or will I run into a problem if I don't use the "^." Pointer? This may be a well-known behavior, but the first time I came across this.

+6
source share
4 answers

It is perfectly healthy and safe to lower the carriage. Of course, logic requires a carriage, but since the expression x.value has no meaningful internal interpretation in its own x.value , the compiler will assume that you actually mean x^.value . This function is part of the so-called extended syntax. You can read about it in the documentation .

+9
source

When Valid Syntax is in effect (default), you can omit the carriage by reference to pointers.

+4
source

Delphi has supported this syntax for nearly two decades. When you use the operator . , the compiler will use the ^ operator implicitly. Both styles are true. There is no way for your program to do the wrong thing, because there is no case where the presence or absence of ^ will affect the interpretation of a subsequent statement . .

Although this behavior is controlled by the advanced syntax option, no one ever disables this option. You can trust that it is installed in all contexts. It also controls the availability of the implicit Result variable, and character pointers are compatible with array syntax.

+4
source

This is called implicit dereferencing of pointers for structured types and is inherited from Delphi 1. This language extension is intended to access class members (classes of structured types as well as instances are implicit pointers) only using the membership operator ( . ), Avoiding the requirement for an explicit dereferencing operator ( ^ ).

You can safely rely on the presence of this extension in all Delphi compilers. For added flexibility, you can check for this extension using the conditional directive $IFOPT X+ .

+1
source

Source: https://habr.com/ru/post/946209/


All Articles