Delphi 10.1, Function that only accepts an integer interval in the variable

Asked

Viewed 153 times

2

It sounds easy, but I’m not getting it. I want to be able to define a type of variable when creating a Function or Procedure, but only accepting integers between 1 and 4 for example during the Function/Procedure call. Numbers that can already be used in it.

something like:

function Algo(TAlgo: array [1...4] of integer);

where you won’t even agree to compile if I call:

Something(5);//return error, nor accept compile
Something(1);//ok
Something(2);//ok
Something(3);//ok
Something(4);//ok


I was able to approximate, but I’m trying to simplify the code below, as example above. So far I have achieved something similar, creating a Type, as below:

I created a Type:

    TQtd = (xUma, xDuas, xTres, xQuatro);

And within Function, a var and a case:

var
  iQtd:Integer;
...
  case Precision of
    xUma: iQtd := 1;
    xDuas: iQtd := 2;
    xTres: iQtd := 3;
    xQuatro: iQtd := 4;
  end;

So I use the iQtd variable and get what I need, calling Function this way:

functionTal(xTres);

There is how I create, already specifying that it is integer, accepting only 1 to 4?

1 answer

7


You can create a type using an integer range, e.g.:

Type
  TAteQuatro = 1..4;

  procedure Teste(valor: TAteQuatro);
  begin
    Writeln(valor);
  end;
begin
  Teste(4); //Compila
  Teste(5); //[dcc32 Error] Rangezera.dpr(20): E1012 Constant expression violates subrange bounds
end.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.