rangepascalfreepascallazarusdelphi

Checking to see if a number is within a range in free pascal


I am trying to figure out the correct way of passing an example that was using Free Pascal case statements to a simple if statement.

Using case would be

begin usingCaseStatements;

var
  user_age : Integer;

begin

  Writeln('Please enter your age');
  Readln(user_age);

  case user_age of
  1..12 : Writeln('You are too young');
  else
    Writeln('Invalid input');
  end;

  Writeln('Please any key to terminate the program');
  Readln();
end.

-----Using an if statement--------

begin usingCaseStatements;

var
  user_age : Integer;

begin

  Writeln('Please enter your age');
  Readln(user_age);

  if user_age in 1..12 then
    Writeln('You are too young')
  else
    Writeln('Invalid input');
  Writeln('Please any key to continue');
  Readln();
end.

I have tried replacing the "in" inside the if-statement snipet with no luck whatsoever at one point I tried doing if (user_age = 1..12) thenand it only gave me an error, the compiler states that the statement is waiting for ')' but that it found .. instead. I am extremely new to FPC so help and tips would be greatly appreciated.


Solution

  • IN tests for sets, not ranges. As TLama already commented, you can define a set containing the range using [1..12].

    Most PC Pascals only support set sizes up to 256 elements though, so a solution as recommended by josifoski will be more practical long term.