Jump to content
havrlisan

Using inline variables inside loops

Recommended Posts

Will there be any issues with declaring inline variables inside loops? Here's an example:
 

procedure Sample(const AFixedArray: TSomeFixedArray);
begin
  for var I = 0 to 10 do
  begin
    var LInlineVariable := TSomeFixedArray[I];
    // do something
  end
end

 

Is it possible that the compiler will allocate more memory than needed, or something in that context? This seems to me like the only way the inline variable feature may produce issues.

Share this post


Link to post

you're declaring the same variable 10 times, I don't think it's possible the way you mean, you could alternatively use a record type, and then call it in an array, like:
 

type
  myRec = Record
          myVar : String[20];
          End;

[...]

var
  ArrRec : Array Of myRec;

[...]

procedure Sample(const AFixedArray: TSomeFixedArray);
begin
  SetLength(ArrRec,10);

  for var I = 0 to 10 do
  begin
    ArrRec[I].myVar := 'xyz'+I.ToString;
    // do something
  end
end

 

Share this post


Link to post
26 minutes ago, Minox said:

you're declaring the same variable 10 times, I don't think it's possible the way you mean, you could alternatively use a record type, and then call it in an array, like:
 


type
  myRec = Record
          myVar : String[20];
          End;

[...]

var
  ArrRec : Array Of myRec;

[...]

procedure Sample(const AFixedArray: TSomeFixedArray);
begin
  SetLength(ArrRec,10);

  for var I = 0 to 10 do
  begin
    ArrRec[I].myVar := 'xyz'+I.ToString;
    // do something
  end
end

 

That's just unnecessarily complicating things. I'd generally declare the variable before the loop (whether it be before begin or as an inline variable, it doesn't matter), I am just wondering if the compiler is able to interpret the variable declaration as it should (?) in loops.

Share this post


Link to post

firstly, I think that not right way to do it, but, as the var is allocated on stack, and the var-life is "short"!

then, the next round, var will "dead", and create a new var on memory same address (if not used yet)!

 

bds_QiyfQ9uYSw.gif

  • Like 1
  • Thanks 2

Share this post


Link to post
1 hour ago, programmerdelphi2k said:

firstly, I think that not right way to do it, but, as the var is allocated on stack, and the var-life is "short"!

then, the next round, var will "dead", and create a new var on memory same address (if not used yet)!

 

bds_QiyfQ9uYSw.gif

Very good explanation, thank you!

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×