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 IfNote: 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
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
SleepExample 2: "Guess the number" game
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
SleepDialect Differences
- In
-lang qband-lang fblite, variables declared inside anIf..Thenblock have procedure-wide scope. - In
-lang fband-lang deprecated, variables declared inside anIf..Thenblock are visible only inside the block. - In
-lang qb, if there is a new line or single-line comment directly afterThen, theIfwill be multi-line. - In
-lang fband-lang fblite, a new line, comment, colon, orRemafterThenmakes it multi-line.
Differences from QB
End Ifwas not supported in single-lineIfs in QBASIC.