9.2 Conditional statements

A conditional statement is a statement that execute different statements depending on the value of a boolean expression.

If:then

The if:then statement used in previous sections is an example of a conditional statement. The code below shows a sketch of a definition of if:then as a control method.

if(cond: var boolean):then{thenPart:< Object}:
   ...

As mentioned, if:then is a built-in primitive control method in qBeta and cannot be defined in terms of other language mechanism.

Defining if:then:else

The if:then:else is an example of a control method that may be define as method in qBeta. You may find the following definition in the qBeta library:

if(cond: var boolean):then{thenPart:< Object}
                     :else{elsePart:< Object}:
   if (cond) :then  
      thenPart
      leave(if:then:else)
   elsePart

The control method has the following structure:

  • The name of the control method is if:then:else.
  • It has three parameters, cond, which is a boolean, thenPart, which is a virtual Object, and elsePart, which also is a virtual Object.
  • The parameters are specified using the fat-comma syntax as described in section .
  • The first item in the main-part of the abstraction is an if-then statement.
  • If the boolean cond is true then the virtual thenPart is executed followed by leave(if:then:else), which terminates the execution of if:then:else.
  • If the boolean cond is false then the virtual elsePart is executed.

Consider an invocation of if:then:else:

if (amount <= balance) :then
   balance := balance - amount
 :else
   console.print("The balance is less than the amount")

Execution of the if:then:else takes place as follows:

  • The expression (amount <= balance), the statement balance := balance - amount, and the statement console.print("The balance is less than the amount") are the actual parameters (arguments) of the invocation of if:then:else.
  • The boolean expression amount <= balance is evaluated and assigned to the parameter cond.
  • The statement balance := balance - amount is a further binding of the virtual thenPart.
  • The statement console.print("...") is a further binding of the elsePart.