Operators

Chris Wild

Last modified: Jul 22, 2016
Contents:

1 Description

2 Examples

2.1 Relational and Equality Operators

The relational operators are <, <=, >, >=.

The Equality operators are ==, !=.

Given two numbers, a and b , the following table lists examples of logic expressions formed using the relational and equality operators.

Example Meaning
a == b a is equal to b
a < b a is less than b
a > b a is greater than b
a <= b a is less than or equal to b
a >= b a is greater than or equal to b
a != b a is not equal to b

2.2 Logical Operators

The logical operators include && and ||

Given numbers a, b, c, and d. The following table lists examples combining relational and logical operators.

Example Meaning
(a = = b) && (c < d) true if a is equal to b AND c is less than d
a = = b && c < d same as the above (see precedence rules)
(a > b) || (c != d) true if a is greater than b OR if c is not equal to d
a > b || c != d same as the above (see precedence rules)

3 Precedence Rules

Motivation: Consider the following expression:

a > b && b == c || c < d

There are two interpretations which give two different results

(a > b && b > c) || c < d //do first two relational operators first, then the last, value is true
a > b && (b >c || c < d)  // do last two relational operators first, then the first, value is false

Precedence rules let the compiler decide which interpretation to take. The precedence rules are:

By these rules, the first interpretation is used.

However, if in doubt, use parenthesis to make your meaning clear to yourself and other programmers.

4 Tips

5 Experiment

Difference between the assignment and equality

#include <iostream>

using namespace std;

int main()
{
    int i = 4;
    int j = 5;

    if ( i = j) {
        cout << "equal" << endl;
    } else {
        cout << "NOT equal" << endl;
    }
    return 0;
}

Hypothesis: What will this program print out?

If you aren’t sure, compile and run the program to see.

Answer

What is the value of “i” after the “if” statement executes? (you can modify the experiment to output the value)

Answer