Skip to content

IF...THEN

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

Control flow statement for conditional branching.

Syntax

Single-line:

If expression Then [statement(s)] [Else [statement(s)]] [End If]

Multi-line:

If expression Then
    [statement(s)]
[ElseIf expression Then]
    [statement(s)]
[Else]
    [statement(s)]
End If

Note: EndIf (without blank) is also supported for backward compatibility with QB.

Description

If...Then is a way to make decisions. It executes code only if a condition is true, and can provide alternative code to execute based on more conditions.

expression can be:

  • A conditional expression: x = 5
  • Multiple conditions with logical bitwise operators: x >= 5 And x <= 10
  • Multiple conditions with short-circuit operators: y <> 0 AndAlso x \ y = 1
  • Any numerical expression (0 = False, non-zero = True)

Both multi-line and single-line Ifs can be nested. The multi-line syntax allows several ElseIfs (but none after an Else). If the condition of the If is not true, those of ElseIf blocks are tested in succession.

In the -lang fb and -lang fblite dialects, colons (:) can be used instead of newlines to construct multi-line If blocks on a single line.

Note: The single-line If...Goto syntax is deprecated and exists only for QB compatibility.

Examples

Example 1: Single-line with multiple statements

vb
Dim As Double d, r
r = -1
d = 2
If d > 0 Then r = Sqr(d) : Print "square root computed:" Else r = 0 : Print "square root not computed:"
Print r
Sleep

Example 2: "Guess the number" game

vb
Dim As Integer num, guess
Randomize
num = Int(Rnd * 10) + 1
Print "guess the number between 1 and 10 (or CTRL-C to abort)"
Do
    Input "Guess"; guess
    If guess > 10 OrElse guess < 1 Then
        Print "The number can't be greater then 10 or less than 1!"
    ElseIf guess > num Then
        Print "Too high"
    ElseIf guess < num Then
        Print "Too low"
    Else
        Print "Correct!"
        Exit Do
    End If
Loop
Sleep

Dialect Differences

  • In -lang qb and -lang fblite, variables declared inside an If..Then block have procedure-wide scope.
  • In -lang fb and -lang deprecated, variables declared inside an If..Then block are visible only inside the block.
  • In -lang qb, if there is a new line or single-line comment directly after Then, the If will be multi-line.
  • In -lang fb and -lang fblite, a new line, comment, colon, or Rem after Then makes it multi-line.

Differences from QB

  • End If was not supported in single-line Ifs in QBASIC.

See Also

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