Operators That Make Decisions

 

Relational Operators:

 

 

Relational operators return a Boolean or true / false result.

 

Caution:

Beware the common error involvint the equal sign!

The following statement,

 

If (amount = 123)

          //  . . . the “then clause”

 

does NOT do what you intended. It simply assigns the value 123 to the variable “amount” and then executes the “then clause”.

 

Conditional Operators:

Also known as the ternary operator.

 

<expression1>  ?  <expression2>  :  <expression3>

 

The evaluation tests the first expression.

If that expression is true, the resulting expression is assigned the value of the second expression, expression2 – otherwise, the resulting expression is assigned a value equal to that of expression3.

Example:

amountdue = overdue  ?  dues * 1.10  :  dues;

 

If the variable, overdue, evaluates to true,  then the variable “amountdue” is assigned the value from the expression “dues * 1.10”. Conversely, if the variable, overdue, evaluates to false,  then the variable “amountdue” is assigned the value of “dues”.

 

 

Logical Operators:

 

 

Logical operators are used to evaluate combinations of Boolean variables.

 

flots && jets   //evaluates to true if both are non-zero (true)

flots || jets   // evaluates to true if either is non-zero (true)

!flots             // true if flots is zero (false)

 

A Programming Trick!

!!blob

Using the NOT operator twice has the effect of first converting the integral variable, blob, to the logical inverse of its current value. For example, working right to left, if blob is zero, the  “!” operator converts that zero to the Boolean true. The next NOT operator is applied to invert the logical state of the expression “!blob”. In our example, that would result in false. As you can see, the net effect of this is to convert an integral value to a Boolean.