Control flow statement for conditional branching
Syntax
If expression Then [statement(s)] [Else [statement(s)]] [End If]
or
If expression Then : [statement(s)] [Else [statement(s)]] : End If
or
If expression Then
[statement(s)]
[ ElseIf expression Then ]
[statement(s)]
[ Else ]
[statement(s)]
End If
Description
If...Then is a way to make decisions. It is a mechanism to execute code only if a condition is true, and can provide alternative code to execute based on more conditions.
The expression is always evaluated completely (no short-circuit evaluation), so it is necessary to separate potentially unsafe expressions with extra levels of
If blocks.
Both multi-line and single-line
Ifs can be nested. In the latter case, the optional
End Ifs can be useful to control where nested
Ifs begin and end.
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.
Example
'e.g. here is a simple "guess the number" game using if...then for a decision.
Dim x As Integer, y As Integer
Randomize Timer
x = Rnd * 11 'Create a random number between 0 and 10.999...
Print "guess the number between 0 and 10"
Do 'Start a loop
Input "guess"; y 'Input a number from the user
If x = y Then
Print "right!" 'He/she guessed the right number!
Exit Do
ElseIf y > 10 Then 'The number is higher then 10
Print "The number cant be greater then 10! Use the force!"
ElseIf x > y Then
Print "too low" 'The users guess is to low
ElseIf x < y Then
Print "too high" 'The users guess is to high
End If
Loop 'Go back to the start of the loop
Dialect Differences
In the
-lang fb and
-lang fblite dialects, if there is a new line, a single-line comment (
'), a colon (
:), or a
Rem statement directly after THEN, then the IF will be multi-line. Any other statement will result in a single-line IF.
In the
-lang qb dialect, if there is a new line or a single-line comment (
') directly after THEN, then the IF will be multi-line. A colon, a
Rem or any other statement will result in a single-line IF.
Differences from QB
- END IF was not supported in single-line IFs in QBASIC.
See also