8

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?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
user1000441
  • 85
  • 1
  • 1
  • 3

3 Answers3

26

If Number has some integer data type, then:

case number of
5 .. 10: lblAnswer.Caption := 'in range';
else     lblAnswer.Caption := 'out of range';
end;
da-soft
  • 7,670
  • 28
  • 36
  • thx so i had to leave out the long code ... and just go to numbers alrite make sense now thx alot – user1000441 Oct 18 '11 at 05:51
  • 4
    Of course this will only work if number is an Integer and not a floating point type. – Uwe Raabe Oct 18 '11 at 05:58
  • 1
    @user1000441 if this answer solved your problem, you should mark it as "accepted answer" so others know your problem is solved. – HpTerm Jul 10 '14 at 08:29
8

A small correction:

case (number >= 5) and (Number <= 10) of
  true:lblAnswer.Caption := 'in range';
  false:lblAnswer.Caption := 'out of range';
end;
user997287
  • 163
  • 4
  • 3
    +1 This is the correct way of coding it using `case` but honestly there is no interest of using a `case` here instead of a `if .. then` statement. – Arnaud Bouchez Oct 18 '11 at 06:24
  • @peter, this code here is correct. But Arnaud means that an if then statement is more appropriate. – LU RD Oct 18 '11 at 06:44
  • 1
    Either da-soft's answer or an if statement. Very odd to write case with a boolean condition. I originally thought this was syntax error it looked so weird. This answer works but you'll never see it in anyone else's code. – David Heffernan Oct 18 '11 at 07:27
  • 2
    -1. I cannot endorse Boolean case statements. They can confuse the compiler, which in turn confuses the programmer. (For lengthy discussions on this topic, do a [newsgroup search for Boolean case statements](http://groups.google.com/groups/search?q=boolean+case+statement+kennedy), and include my name in the search terms.) – Rob Kennedy Oct 18 '11 at 15:18
1
Function InRange (Lo,Hi,Val : Integer) : Boolean;
Begin
 Result := (Val>=Lo)And(Val<=Hi);
End;
Jeroen
  • 60,696
  • 40
  • 206
  • 339
Eli Fried
  • 29
  • 1