Advertisement

C Programming Tutorial 36 - Operator Precedence

C Programming Tutorial 36 - Operator Precedence 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.


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!

Subscribe to my newsletter:

Donate!:

~~~~~~~~~~~~~~~Additional Links~~~~~~~~~~~~~~~

More content:
Facebook:
Google+:
Twitter:

Amazing Web Hosting - (The best web hosting for a cheap price!)

c programming,programming,tutorial,36,operator,precedence,order,of,operations,associativity,valid,valid c,declare,variable,caleb,curry,calebthevideomaker2,

Post a Comment

0 Comments