bob_saginowski
bob_saginowski

Reputation: 1429

How to change the values of a boolean array in delphi

I'm making a small Delphi program using Delphi XE5. In my code there is a dynamic boolean array and I'm no able to change the value of some of the arrays elements. I tried to initialize the array after setting it's length but it didn't help. Here is part of the code:

procedure DoSomething(names: array of string);
var startWithA: array of Boolean;
    i: integer;
begin
    SetLength(startWithA, Length(names)); // each element is false by default
    for i := 0 to Length(names) - 1 do begin
       if (names[i].indexOf('A') = 0) then begin
          startWithA[i] := true; // the value is not changed after executing this line
       end;
    end;
end;

Upvotes: 3

Views: 4249

Answers (1)

David Heffernan
David Heffernan

Reputation: 613003

Your code works absolutely fine. Here is the proof:

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

function StartsWithAIndices(const Names: array of string): TArray<Boolean>;
var
  i: Integer;
begin
  SetLength(Result, Length(Names));
  for i := 0 to high(Result) do begin
    if (Names[i].IndexOf('A') = 0) then begin
      Result[i] := true;
    end;
  end;
end;

var
  Indices: TArray<Boolean>;
  b: Boolean;

begin
  Indices := StartsWithAIndices(['Bob', 'Aaron', 'Aardvark', 'Jim']);
  for b in Indices do begin
    Writeln(BoolToStr(b, True));
  end;
  Readln;
end.

Output

False
True
True
False

Perhaps your confusion stems from the fact that you assign to an array that is a local variable and whose values are never read. How can you say that the array values are not modified if you never read from them? Or perhaps you have optimizations enabled and the compiler decided to optimize away the local variable whose values are written to but never read.

As an aside, your function could be written more simply like this:

function StartsWithAIndices(const Names: array of string): TArray<Boolean>;
var
  i: Integer;
begin
  SetLength(Result, Length(Names));
  for i := 0 to high(Result) do begin
    Result[i] := Names[i].StartsWith('A');
  end;
end;

Upvotes: 5

Related Questions