Operators and Precedence

Operators

So assignment statements can look like this:

A = 1.0 + 2.0 / 3.0 * 75.0;

What's the right Answer

2.0 + 4.0 / 3.0

Is it 3.3333 or 2.0?

 

5.0 + 3.0 / 4.0 - 2.0

Precedence

( ) Grouping

*, / Multiplication and division

+ , - Addition and subtraction

Within a level of precedence evaluation is done from left to right.

Examples

5.0 + 3.0 / 4.0 - 2.0

 

4.0 * 3.0 / 2.0 * 6.0

 

15.0 + 2.0 - 6.0 / 2.0 * 4.0

 

Mixed Mode Arithmetic

If you mix integers and floats you sometimes get unexpected results. In C++, as in most programming languages, there are rules for the result type given the operand types.

 

Float and a float results in a float.

The combination of an integer and a float also results in a float.

 

The combination of an integer and an integer results in an integer. This sounds fine to start with but what is 3/4? It's zero. Any fractional part is discarded. This results in problems at times:

 

1/2*alpha

 

Will come out as a 0!