# C Programming Tutorial 36 - Operator Precedence

Caleb Curry
Published at : 02 Jan 2021
11530 views
301
1

You may have heard from math class of this fancy thing called order of operations. We discussed this in a previous video so I'm not going to waste your time by repeating myself, but I am going to look at the same concept from a bigger point of view.

The point of the order of operations is to say which operators happen first and from which direction. For example, we know for the c operators, the multiplication happens first. This order in which operators happen is known as precedence. For example, you can say that multiplication has precedence over addition. And if we have multiple multiplications in one expression, it happens from left to right. The direction of which way a specific operator happens is known as the operator's associativity.

This is a good reference page that lists the C operators, their precedence, and their associativity.
http://en.cppreference.com/w/c/language/operator_precedence

A good example of left associativity is if we do something like this:

int x, y;
x = y = 5;

This is valid C and shows that we can declare two variables on one line and also assign values on one line. In general, I try to do things one step at a time, but sometimes you will encounter statements like these.

Although either way the result is going to be that x and y are both equal to 5. The order in which this happens is from the left and from the right. First, y = 5 will happen. Next, x = y will happen.

If you have two operators on one line, the first thing that happens is the operator with the highest precedence. For example:

int z = 20;
y = 2;
x = -y + z;

This could either be evaluated as:

x = -(y + z); //x = - 22

or

x = (-y) + z; //x = 18

The second is the one that will happen according to the operator precedence.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Support me! http://www.patreon.com/calebcurry

Donate!: http://bit.ly/DonateCTVM2.

More content: http://CalebCurry.com

Amazing Web Hosting - http://bit.ly/ccbluehost (The best web hosting for a cheap price!)