[In this post I will talk about one subtle difference between the operator precedence in C and Matlab, you can start from the third paragraph if you are familiar with the notion of operator precedence.]

Operator Precedence is really important. I have learnt it the hard way earlier this week. I decided to write about it, hopefully after reading this, you will never fall into the same trap like I did.

For those who are not familiar with the terminology, operator precedence (also called the order of operation) refers a set of rules that defines the order of calculations/procedures should follow in a given mathematical operation. It’s basically what we all learned in first grade. Multiplication has higher priority than addition. 1+2×3 = 7 not 9, because the multiplication operation goes first.

In mathematics, people follow the same rule for operator precedence. However, when it comes to programming, the situation can be a little different. Different programming languages may define operator precedence differently. The specific precedence rule that threw me off involves the comparison operators. In C-style languages, comparison operators are divided into two different categories: (1) the equal comparisons, including equal (==) and not equal (!=) and (2) the unequal comparisons, including smaller than (<), greater than (>), smaller than or equal to (<=), and greater than or equal to (>=). In C-style languages, the unequal comparisons (i.e. >, <, <=, >=) precedes the equal comparisons (i.e. ==, !=).

Therefore,

1<=2==4>3

means

(1<=2)==(4>3)

and will evaluate to be true.

However, in Matlab, the equal comparisons and the unequal comparisons have the same level of priority. The same expression:

1<=2==4>3

will execute from left to right, as:

((1<=2)==4)>3

and evaluate to be false (note, there are also type conversions going on here).

This can be pretty difficult to catch, especially when you are like me, having this hard wired C-style operator precedence in my head and trying to do some complicated matrix comparison in one line of Matlab code.

So, I have learned my lesson: (1) know the operator precedence. (2) parentheses are my friends. (3) break one line of complicated code into several lines of simpler codes when necessary.

I hope you learned something useful, and see you until next time.

google apps fresno stateWonderful post but I was wondering if you could write a litte more on this topic?

I’d be very thankful if you could elaborate a little bit more.

Thank you!