Relational & Logical Operators


Relational operators deal with relationships amongst entities. Logical operators deal with conections amongst boolean quantities. Often relational and logical operators are seen together so in this section they will be discussed together.

The relational operators are shown in the table below.

Operator Meaning
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to

The logical operators are shown in the table below.

Operator Meaning
&& logical and
|| logical or
! logical not

The outcome of relational and logical operators is an integer value.

In generic, all objects can be compared for equality or inequality using operators == and !=. However, the relational, ordering operators <, >, <= and >= can only be applied to types that support an order on the type. Since the numeric types support order, all relational operators may be applied to all numeric types.

The operands of the operators && ||, and ! must be of type integer. The truth tables of these operators are as follows (where 't' stands for 'true' and 'f' stands for 'false').

p q p&&q p||q !p
f f f f t
f t f t t
t f f t f
t t t t f

The next program makes use of a number of relational and logical operators.

// relational_operators.tecst - relational and logical operators

generic relational_operators
{
    relational_operators()
    {
        i = 5
        l = 10
        s = "i = " + i.to_string() + " l == " + l.to_string() 
        s.println()

        if i < l  {s = "i < l" s.println()}
        if i <= l {s = "i <= l" s.println()}
        if i != l {s = "i != l" s.println()}
        if i == l {s = "i == l" s.println()}
        if i > l  {s = "i > l" s.println()}
        if i >= l {s = "i >= l" s.println()}

        b1 = true
        b2 = false
        s = "b1 = " + b1.to_string() + " b2 = " + b2.to_string()
        s.println()

        if b1 && b2    { s = "b1 && b2" s.println()}
        if !(b1 && b2) { s = "!(b1 && b2)" s.println()}
        if b1 || b2    { s = "b1 || b2" s.println()}
        if !b2    { s = "!b2" s.println()}
    }
}

The output of the program is shown below.

i = 5 l == 10
i < l
i <= l
i != l
b1 = 1 b2 = 0
!(b1 && b2)
b1 || b2
!b2

From the output, it may be inferred which expressions evaluated to true.