How can I test that a value is within a range with a "case" statement instead of an "if" statement?

16.1k Views Asked by At

Can the following if statement be converted to a case statement?

if (Number >= 5) and (Number <= 10) then
  lblAnswer.Caption := 'in range'
else
  lblAnswer.Caption := 'out of range';

My Answer :

Yes it can

case (number >= 5) and (Number <= 10) of
  lblAnswer.Caption := 'in range';
  lblAnswer.Caption := 'out of range';
end;

Is this correct?

3

There are 3 best solutions below

3
On

If Number has some integer data type, then:

case number of
5 .. 10: lblAnswer.Caption := 'in range';
else     lblAnswer.Caption := 'out of range';
end;
4
On

A small correction:

case (number >= 5) and (Number <= 10) of
  true:lblAnswer.Caption := 'in range';
  false:lblAnswer.Caption := 'out of range';
end;
0
On
Function InRange (Lo,Hi,Val : Integer) : Boolean;
Begin
 Result := (Val>=Lo)And(Val<=Hi);
End;