Table of Contents

10.2.1 Conditional selection - IF control structure

This chapter describes the following variants of the IF control structure:

10.2.1.1 Syntax

The syntax for the IF control structure in the second part represents the cases in which only one (conditional) selection is formulated in a row:

IF Expression [ { AND IF | OR IF } Expression ... ] [ THEN ] 
  ... 
[ ELSE IF Expression [ { AND IF | OR IF } Expression ... ] [ THEN ] 
  ... ] 
[ ELSE 
  ... ] 
ENDIF 
IF Expression [ { AND IF | OR IF } Expression ... ] THEN ... 
IF Expression [ { AND IF | OR IF } Expression ... ] THEN ... ELSE …

10.2.1.2 Notes on the syntax

The following examples show mainly Gambas source code excerpts and are commented on briefly. Some of the examples are preceded by pseudo-code, which is intended as a readable interpretation of the syntax of the IF-control structure (? 10.2.1.1 syntax).

10.2.1.3 Examples for one-sided selection

In one-way selection, the statement or statement block is only executed if the expression is true. There is no alternative.

IF expression is true, THEN 
     execute this statement(s) 
END of the selection 
IF Len(txbFarbwert.Text) = 0 THEN 
   txbFarbwert.MaxLength = 6 
   Return
ENDIF
IF expression is true, THEN execute this instruction(s) 
IF Key.Code = Key.F1 THEN btnHelp_Click()
IF expression is NOT true, THEN execute this instruction(s) 
IF NOT txbFarbwert.Text Then Message.Warning("Enter a color value!") 

10.2.1.4 Examples for two-sided selection

If variant 1 was selected via the RadioButton, then this variant is used for calculation, otherwise the second variant is used:

IF expression is true, THEN 
     Execute this statement (s) (and exit the control structure) 
ELSE 
     Execute those statement(s) 
End of selection
IF optV1.Value = True THEN 
   Calculate_V1(iAZahl, iEZahl)
ELSE 
   Calculate_V2(iAZahl, iEZahl)
ENDIF

The alternative notation of the IF control structure in one line triggers a syntax error in the second line, because no ENDIF is allowed at the end of the line:

(1)	IF optV1.Value = True THEN Calc_V1(iAZahl, iEZahl) ELSE Calc_V2(iAZahl, iEZahl)
(2)	IF optV1.Value = True THEN Calc_V1(iAZahl, iEZahl) ELSE Calc_V2(iAZahl, iEZahl) ENDIF ' Error!

10.2.1.5 Examples for Multiple Selection

Here is an IF control structure for three (→ k=3) incompatible cases in which you are sure that exactly one of the three cases applies:

IF expression_1 is true, THEN 
     Execute this statement (s)_1 (and exit control structure) 
ELSE IF expression_2 is true, THEN 
      Execute this statement (s)_2 (and exit control structure) 
... 
ELSE IF expression_k is true, THEN 
      Execute that statement (s)_k 
END OF the selection
Public Function Calculate(fP As Float, fQ As Float) As Variant[]
  Dim fDiskriminante As Float = 0
  Dim fX1, fX2 As Float
  Dim fXC1, fXC2 As Complex    
  fDiskriminante = (fP * fP) / 4 - fQ
  IF Sgn(fDiskriminante) = 1 THEN ' D>0
     fX1 = - fP / 2 - Sqr(fDiskriminante)
     fX2 = - fP / 2 + Sqr(fDiskriminante)
     Return [fX1, fX2]
  ELSE IF Sgn(fDiskriminante) = 0 Then ' D=0
     fX1 = - fP / 2
     fX2 = fX1
     Return [fX1, fX2]
  ELSE IF Sgn(fDiskriminante) = -1 Then ' D<0
     fXC1 = Complex(- fP / 2, - Sqr(- fDiskriminante))
     fXC2 = fXC1.Conj()
     Return [fX1, fX2]
  ENDIF
End ' Calculate(fP As Float, fQ As Float) As Variant[]

Example

IF expression_1 is true, THEN 
     Execute this statement(s)_1 (and exit control structure) 
ELSE IF expression_2 is true, THEN 
      Execute this statement(s)_2 (and exit control structure) 
... 

ELSE unconditionally execute that instruction(s)! 
END of the selection
Public Sub GetStatus(sStatus As String)
  IF sStatus Like "[+Pp]*" THEN
     Message.Info(IIf(sStatus Begins "+", "Status: positiv", "Status: " & sStatus))
  ELSE IF sStatus Like "[-Nn]*" THEN
     If sStatus Begins "-" Then sStatus = "negativ"
     Message.Info("Status: " & sStatus)
  ELSE
     Message.Error("Der Status konnte NICHT ermittelt werden!")
  ENDIF
End ' GetStatus(sStatus As String)

The unconditional use of ELSE is often used for error messages.

Example

Several expressions linked via' AND IF' or' OR IF' are used in a procedure in the following examples:

WENN Ausdruck_1 wahr ist UND WENN auch Ausdruck_2 wahr ist, DANN 
     diese Anweisung(en) ausführen 
ENDE der Auswahl
Public Sub txbFarbwert_KeyPress()  
 
  IF (Key.Control AND Key.Code = Key.F1) THEN btnHelp_Click() 
 
  IF (Key.Code = Key.Return OR Key.Code = Key.Enter) AND IF (txbFarbwert.Text) THEN
     Message.Info("The characters entered are:\n\n" & Upper(txbFarbwert.Text)) 
 
     IF Left(txbFarbwert.Text, 1) = "&" THEN 
        txbFarbwert.MaxLength = 7 
     ELSE       
        txbFarbwert.MaxLength = 6      
     ENDIF 
 
  ENDIF ' Key.Code = Key.Return OR Key.Code = Key.Enter AND ...? 
 
  IF (Key.Code = Key.BackSpace) AND IF (Len(txbFarbwert.Text) > 0) THEN 
     txbFarbwert.Text = Left(txbFarbwert.Text, Len(txbFarbwert.Text) - 1) 
  ENDIF ' Key.Code = Key.BackSpace AND Len(txbFarbwert.Text) > 0 ? 
 
' Permissible characters for a color value in hexadecimal representation 
  IF Key.Text NOT Like "[&0-9a-fA-F]" THEN 
     Stop Event 
  ENDIF ' Key.Text NOT Like "[&0-9a-fA-F]" 
 
End ' txbFarbwert_KeyPress()

Example

IF expression_1 is true OR IF expression_2 is true, THEN 
     execute this statement(s) 
END of the selection 
Private Sub ResultSave()
  Dim sMessage1, sMessage2 As String
 
  Dialog.Path = sScriptFilePath
  Dialog.Title = ("Save the result matrix!")
  Dialog.Filter = ["*.fit", ("GnuPlot-Skript-Datei"), "*", ("Alle Dateien")]
  If Dialog.SaveFile() Then
     Message.Warning("Saving has been cancelled!") ' Cancel button pressed!
     Return 
  Else
     If (File.Ext(Dialog.Path)) OR IF (File.Ext(Dialog.Path) <> "fit") Then
        Dialog.Path = File.SetExt(Dialog.Path, "fit")
     Endif
     File.Save(Dialog.Path, txaErrorAndFit.Text)
     Finally
     btnSaveScriptFile.Enabled = False
     Catch
     sMessage1 = ("The result file ")
     sMessage2 = (" can NOT be saved!")
     Message.Error("FEHLER!" & Chr(10) & sMessage1 & File.Name(Dialog.Path) & sMessage2)
  Endif ' Dialog.SaveFile() = True ? 
 
End ' ResultSave()

Hints:

10.2.1.6 Excursus

The following examples - but also some of the examples mentioned above - can only be understood if you know the content of the term expression in Gambas. In the documentation for' Expression' you will find, among other things, the following:

An expression is a value (a constant, a predefined constant, a variable or the result of a function), which may optionally be preceded by certain operators depending on the type of value, followed by an operator and another value, and so on.

Translated and provided with examples it reads like this:

An expression is a value: a constant (*1), a predefined constant (*2), a variable (*3) or the result of a function call (*4), which can be preceded or followed by certain optional operators (*5) - depending on the type of value - and so on (*6).

Examples of the cases marked (*1) to (*6):

(*1) → 5 or “Test”
(*2) → gb. Integer
(*3) → iIndex
(*4) → Pi(2)
(*5) → NOT bIsActive
(*6) → NOT bIsActive OR IF (iLevel < iMinLevel)

The following applies to expressions associated with the IF control structure:

The IF control structure checks the truth value of an expression. For objects, zero is also the characteristic value for determining the truth value. In all cases, 0 means false and everything else is true.

Examples

Public Sub btnTest_Click()
  Dim iInteger As Integer
  
  Print iInteger  
  IF iInteger THEN
     Print "JA"
  ELSE
     Print "NEIN"
  ENDIF
'--------------------------------------------------------
  IF txbPingNumber.Text THEN 
     Print "TEXTBOX ENTHÄLT TEXT."
  ELSE
     Print "TEXTBOX ENTHÄLT KEINEN TEXT."
  ENDIF
'--------------------------------------------------------
  IF txbPingNumber THEN 
     Print "DAS OBJEKT 'txbPingCount' EXISTIERT"
  ELSE
     Print "DAS OBJEKT 'txbPingCount' EXISTIERT NICHT"
  ENDIF
'--------------------------------------------------------
  IF $hPing THEN 
     Print "DER PING-PROZESS LEBT..."
  ELSE
     Print "VOM PING-PROZESS IST NICHTS ZU SEHEN..."
  ENDIF
'--------------------------------------------------------
  TRY File.Save("/usr/local/backup.bak", txaOutput.Text)
  IF ERROR THEN
     Print "Fehler: "; Error.Text; " - "; Error.Where
     Return
  ENDIF

End ' btnTest_Click()

ERROR alone/ is a keyword of the language Gambas. True is returned if the last TRY statement triggered an error. Minisini advises using ERROR only in this context.

These outputs were displayed in the console of the Gambas IDE:

0
NO
THE TEXTBOX CONTAINS TEXT.
THE OBJECT' txbPingCount' EXIST
OF THE PING PROCESS IS NOT VISIBLE....
ERROR: Access forbidden - FMain. btnTest_Click.135

Download