#514 – Examples of Operator Precedence

Each operator has an associated precedence, which indicates the order in which the operators are evaluated when evaluating the  expression.

For example, because multiplicative (*, /, %) operators have a higher precedence than additive (+, -) operators, the multiplication in the expression below happens before the addition, so the answer is 34.

int result = 4 + 5 * 6;

If we want the addition to happen first, we can change the precedence by using parentheses.

// Result = 54
int result = (4 + 5) * 6;

Here are some other examples of operator precedence.

            // Negation operator has higher precedence than conditional operators
            bool res = !false || true;    // true  (negation operator evaluated first)
            res = !(false || true);       // false (conditional OR evaluated first)

            // && has higher precedence than ||
            bool res = true || false && false;    // true
            res = (true || false) && false;       // false
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: