Skip to content

SELECT CASE

Source: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgSelectcase Last revised: 2021-09-28

Conditional statement block.

Syntax

Select Case expression
[Case expressionlist]
    [statements]
[Case Else]
    [statements]
End Select

or (optimized integer-only form):

Select Case As Const integer_expression
[Case constant | enumeration]
    [statements]
[Case Else]
    [statements]
End Select

Description

Select Case executes specific code depending on the value of an expression. The expression is evaluated once, then compared against each Case in order. The code inside the matching Case branch is executed and the program skips to after End Select.

  • Case Else matches any case not already matched.
  • If no Case matches and there is no Case Else, the entire block is skipped.
  • Exit Select can be used to escape the block.

Note for C users: Select Case works like a switch where all cases have a break at the end. There is no fall-through.

Besides integer types, floating-point and string expressions are supported with the first syntax.

Expression List Syntax

{ expression | expression To expression | Is relational_operator expression } [, ...]
  • expr — equality match.
  • expr1 To expr2 — range match (inclusive).
  • Is relop expr — relational match (=, >, <, <>, <=, >=).
  • Multiple checks per Case separated by commas.

Examples:

vb
Case 1                 ' constant
Case 5.4 To 10.1       ' range
Case Is > 3            ' relational
Case 1, 3, 5, 7 To 9   ' set of values
Case x                 ' variable value

Select Case As Const

If As Const is used, only integer constants and enumerations are supported in the Case list. "To" ranges are supported, but "Is" relational operators are not. A jump table is created, making this form faster than regular Select Case.

The range of values is limited: after converting to uinteger, largest value ≤ smallest value + 8191.

Examples

vb
Dim choice As Integer

Input "Choose a number between 1 and 10: "; choice

Select Case As Const choice
Case 1
    Print "number is 1"
Case 2
    Print "number is 2"
Case 3, 4
    Print "number is 3 or 4"
Case 5 To 10
    Print "number is in the range of 5 to 10"
Case Else
    Print "number is outside the 1-10 range"
End Select

Dialect Differences

  • In -lang qb and -lang fblite, variables declared inside a Select..End Select block have procedure-wide scope.
  • In -lang fb and -lang deprecated, variables are visible only inside the block.

Differences from QB

  • Select Case As Const did not exist in QB.
  • In an expr1 To expr2 case, QB would always evaluate both expressions even if expr1 was higher than the original.

See Also

Translated from FreeBASIC official docs. Contact us for removal if infringed.
FreeBASIC is an open-source project, not affiliated with Microsoft