Recent

Author Topic: [SOLVED] Casting array type  (Read 5319 times)

Dibo

  • Hero Member
  • *****
  • Posts: 1057
[SOLVED] Casting array type
« on: February 25, 2011, 04:02:49 pm »
Hi,

I can't understand casting arrays as method argument. For example, I have this code:
Code: Pascal  [Select][+][-]
  1. type
  2.   TMyArrayOfString = array of string;
  3.  
  4.   { TForm1 }
  5.  
  6.   TForm1 = class(TForm)
  7.     Button1: TButton;
  8.     procedure Button1Click(Sender: TObject);
  9.   private
  10.     { private declarations }
  11.   public
  12.     { public declarations }
  13.     procedure Test(S: TMyArrayOfString);
  14.   end;
  15.  
  16. var
  17.   Form1: TForm1;
  18.  
  19. implementation
  20.  
  21. {$R *.lfm}
  22.  
  23. { TForm1 }
  24.  
  25. procedure TForm1.Button1Click(Sender: TObject);
  26. const
  27.   tmp: array[0..1] of string = ('one', 'two');
  28. begin
  29.   //Test(['one', 'two']); <-- this doesn't work
  30.   Test(tmp);
  31. end;
  32.  
  33. procedure TForm1.Test(S: TMyArrayOfString);
  34. begin
  35.  
  36. end;  
  37.  

Why I can't just call Test(['one', 'two'])? If I call this I get error:
Quote
unit1.pas(38,22) Error: Incompatible type for arg no. 1: Got "Array Of Const/Constant Open Array of Constant String", expected "TArrayOfString"
I must declare temporary constant (which is array of string too) and then send it as argument. If argument is type "array of string" instead of TMyArrayOfString then is ok. Why compilator is so sensitive in this case?

Regards
« Last Edit: February 25, 2011, 10:33:31 pm by Dibo »

Zoran

  • Hero Member
  • *****
  • Posts: 1988
    • http://wiki.lazarus.freepascal.org/User:Zoran
Re: Casting array type
« Reply #1 on: February 25, 2011, 06:14:18 pm »
There is always confusion with open array parameters and dynamic arrays. These two are different things, but the syntax for declaring these looks same.

Take a look at this article: http://rvelthuis.de/articles/articles-openarr.html
In this article find a paragraph named "Confusion".
Swan, ZX Spectrum emulator https://github.com/zoran-vucenovic/swan

Dibo

  • Hero Member
  • *****
  • Posts: 1057
Re: Casting array type
« Reply #2 on: February 25, 2011, 10:33:07 pm »
Great article! Thanks

 

TinyPortal © 2005-2018