Home > OS >  Delphi : [int] in [array] operation is not working
Delphi : [int] in [array] operation is not working

Time:12-23

I have a boolean that needs to be set if a number is present within a certain array. I would like to check for it by doing this :

procedure test();
var
    arr: Array[0..255] of smallint;
    i: smallint;
begin
    arr[0] := 1;
    i := 1;
    if i in arr then
        writeln('IN')
    else
        writeln('OUT')
end;

Running this will get the error : E2015 Operator not applicable to this operand type. But I'm seeing this approach in a lot of stackoverflow answers. Which does this particular implementation not work ? I am missing a compiler directive ? I'm on Delphi 10.3 (Rio).

CodePudding user response:

This is expected.

The in operator is used with sets, not arrays.

If you need to check if an array contains a particular value, you need to iterate over the array in the standard way:

function MyArrayContains(const AArray: array of SmallInt;
  const AValue: SmallInt): Boolean;
begin
  for var i := Low(AArray) to High(AArray) do
    if AArray[i] = AValue then
      Exit(True);
  Result := False;
end;

Using advanced record types and operator overloading, you can, however, define your own array-based record type with in operator support.

  • Related