Operators                        

Programming languages have three types of operators: arithmetic, relational, and logical.


 

Arithmetic

__________________________

Examples:

  • Addition: 2 + 3

  • Multiplication: 2 * 4

  • Subtraction: 4 - 2

  • Exponentiation:  2 ^ 4

  • Real Division:  3 / 2   (equals 1.5)

  • Integer Division: 3 \ 2  (equals 1) -- remainder is discarded

  • Modulus: 6 Mod 4 (equals 2) -- result is the remainder when first number is divided by the second number. If either number is a floating-point number, the result is a floating-point number representing the remainder.

__________________________

Precedence of Arithmetic Operators

If multiple arithmetic operators are included in a single equation, the operations are performed in a specific order:

__________________________

Parentheses can be used to clarify the precedence of operators in an expression, or even alter the precedence.  Parentheses have a higher precedence than any operator.

__________________________

Expression Type

VB expressions have both a type and a value.

Expression Type Value
2 + 3 Integer 5
2 / 3 Single 0.66
"Fred" String "Fred"
"2 + 3" String "2 + 3"
2 > 3 Boolean False
  • For addition, subtraction, or multiplication, if either operand is real, the result is real.

  • For real division (/), the result is real regardless of the types of the operands.

  • For integer division (\), the result is integer regardless of the types of the operands.  

  • For both integer division and modulus, both the operands are rounded to Integers (or Longs) before division is applied.

__________________________

Built-in Functions

  • Int:  converts a real to an integer by truncating the decimal portion

    • Int(2/3) is equal to 0

    • Int(10.1) is equal to 10

    • Int(10.9) is equal to 10

  • Val:  converts a string of numbers to a value

    • Val("23.45") is equal to 23.45

    • Val("13mmm2342") returns 13


 

Relational or Comparison Operators


 

Logical Operators

Logical operators can be used to test multiple conditions by combining simple conditions.

The logical operators are And, Or, and Not.

And T F
T T F
F F F

 

Or T F
T T T
F T F

 

Not  
T F
F T

 

And and Or can only be used to test a complete condition. The following is an invalid statement:

If testCondition = 1 Or 2 Or 4 Then

Instead, a complete condition must be specified:

If ( testCondition = 1 ) Or
   ( testCondition = 2 ) Or
   ( testCondition = 4 ) Then

The same holds true for the And.  The following is invalid:

       If ( grade < 90 and >= 80 ) Then 

Similarly, you cannot write a VB statement like 

        If ( 90 < grade <= 80 ) Then

The correct syntax for such a statement is

        If ( grade < 90 ) And ( grade >= 80 ) Then

 

See the note on the evaluation of compound conditions and short circuiting....


Additional operators


 

Precedence of VB Operators