User Tools

Site Tools


k10:k10.2:k10.2.1:start

10.2.1 Conditional selection - IF control structure

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

  • One-sided selection: IF…THEN…ENDIF
  • Two-sided selection: IF… THEN… ELSE… ENDIF.
  • Multiple selection: IF…. THEN…[ ELSE IF……. ELSE IF] … ENDIF

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

  • For all operands that are not of the Boolean type, you need a relation sign to generate a truth value of expressions (? 10.2.1.6 Excursus).
  • You can use parentheses to override this ranking order so that certain partial expressions are evaluated before other partial expressions. Operations in parentheses have priority. Within the parentheses, however, the normal ranking order of the operators applies again.
  • An expression can be negated with NOT.
  • If no expression is true, then the Else statement will be executed unconditionally, if available.
  • The IF control structure is terminated if the corresponding statements were executed after the first true expression or after the statements were executed in the unconditional' Else' branch or after the' ENDIF' keyword.
  • The' AND IF' and' OR IF' keywords must not be in one line together. You can also nest IF control structures. * The notation from Then to Expression is optional if the following statement is in another line.
  • The spellings' Endif' and' End If' are equivalent.
  • Since Gambas 3.4, you can record the IF control structure in one line - provided that the following statement follows the keyword THEN.

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:

  • OR and' OR IF' as well as AND and' AND IF' are different operators! OR and AND are bitwise operators, while' OR IF' and' AND IF' are logical operators.
  • You can use AND and OR arbitrarily in a complex expression, but only with a variant of the' OR IF' and' AND IF' operators on the same line!
  • If you link several expressions in a complex expression with the' AND IF' operator, they are evaluated from left to right until the first expression is WRONG. This means that the complex expression is WRONG. Only if all linked expressions are TRUE is the complex expression TRUE.
  • If you link several expressions with the' OR IF' operator in a complex expression, they are evaluated from left to right until the first expression is TRUE. This means that the complex expression is TRUE. Only if all linked expressions are WRONG is the complex expression WRONG.

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
  • The variable is initialized with 0 and output as value 0.
  • The NO is logical because it is compared to iInteger <> 0!
  • In the GUI for the console program, 4 was entered as default value for the number of pings in the TextBox with the name txbPingNumber. The issue takes this into account.
  • A TextBox object with the name txbPingNumber exists at runtime and is displayed like this.
  • A ping process with' $hPing = Exec aCommand For Read As “myPingProcess”' was not started - it does not exist. The output is correct.
  • The saving of the specified file in the default path was pushed in a controlled manner, but failed due to missing write permissions in the folder. The error has been intercepted and acknowledged with an error message.

Download

The website uses a temporary session cookie. This technically necessary cookie is deleted when the browser is closed. You can find information on cookies in our privacy policy.
k10/k10.2/k10.2.1/start.txt · Last modified: 23.09.2023 by honsek

Page Tools