Recent

Author Topic: Syntax to access an object through a pointer  (Read 210 times)

XiJinping

  • New member
  • *
  • Posts: 9
Syntax to access an object through a pointer
« on: September 15, 2019, 04:50:33 pm »
Hello all! I have a record TBlock. And variable in some function:

Code: Pascal  [Select]
  1. var
  2.   MyBlock: TBlock
  3. ...
  4. begin
  5.   ...
  6.   MyBlock^.FAttr := ...

and I see that this is compiled as well as:
 
Code: Pascal  [Select]
  1. ...
  2.   MyBlock.FAttr := ...
  3.  
so how is it possible that ^ is optional?! I tried to get FAttr with both syntax and again: the compilation is successful. Is it correct? And why?   %)

Thaddy

  • Hero Member
  • *****
  • Posts: 9184
Re: Syntax to access an object through a pointer
« Reply #1 on: September 15, 2019, 05:36:39 pm »
You are confusing things. TBlock is a record, not a pointer to a record and so does not need de-referencing.
Look at this example:
Code: Pascal  [Select]
  1. program untitled;
  2. // {$mode objfpc} // this fails.
  3. {$mode delphi} // this works.
  4. type
  5.   Tblock = record
  6.     Fattr:integer;
  7.   end;
  8.   PBlock = ^TBlock;
  9.  
  10. var
  11.    myblock:pblock;
  12. begin
  13.   New(MyBlock);
  14.   Myblock.Fattr:=0;
  15.   writeln(myblock.fattr);
  16.   Dispose(myblock);
  17. end.
See the difference with your code?

When compiling in {$mode delphi}, pointer de-referencing is optional.
When compiling in {$mode objfpc}, pointer de-referencing is mandatory.

Whereas this code compiles in both modes, since it does not even use a pointer to the record:
Code: Pascal  [Select]
  1. program untitled;
  2. // {$mode objfpc} // this works.
  3. {$mode delphi} // this works too.
  4. type
  5.   Tblock = record
  6.     Fattr:integer;
  7.   end;
  8. var
  9.    myblock:Tblock;
  10. begin
  11.   Myblock.Fattr:=0;
  12.   writeln(myblock.fattr);
  13. end.
« Last Edit: September 15, 2019, 05:52:46 pm by Thaddy »
also related to equus asinus.

XiJinping

  • New member
  • *
  • Posts: 9
Re: Syntax to access an object through a pointer
« Reply #2 on: September 15, 2019, 05:45:54 pm »
Oh, sorry, true, I am in delphi mode  :-[

EDIT: I will add this link to help to other beginner who will hit the same case: http://docwiki.embarcadero.com/RADStudio/Rio/en/Extended_syntax_(Delphi)
« Last Edit: September 15, 2019, 05:49:21 pm by XiJinping »

Thaddy

  • Hero Member
  • *****
  • Posts: 9184
Re: Syntax to access an object through a pointer
« Reply #3 on: September 15, 2019, 05:53:32 pm »
Oh, sorry, true, I am in delphi mode  :-[

EDIT: I will add this link to help to other beginner who will hit the same case: http://docwiki.embarcadero.com/RADStudio/Rio/en/Extended_syntax_(Delphi)

Better look again. I expanded the examples a little. See above.
also related to equus asinus.