PDA

View Full Version : Bug ? Error in calculating constants



BigWumpus
- 11th October 2005, 13:23
Yesterday i've broken down an interesting bug:

Takt CON 40
Prescaler CON 2
UPM VAR WORD
T8 VAR WORD

UPM=((Takt/Prescaler)*25000/8)/T8

is working wrong, because "(Takt/Prescaler)*25000" is bigger than 16 Bit - but there is no overflow-error !

using
UPM=((Takt/Prescaler)*(25000/8))/T8
works !

PBP 2.44

Dwayne
- 11th October 2005, 21:55
Hello Big Wompus,

BW>>UPM=((Takt/Prescaler)*25000/8)/T8

is working wrong, because "(Takt/Prescaler)*25000" is bigger than 16 Bit - but there is no overflow-error !

using
UPM=((Takt/Prescaler)*(25000/8))/T8
works !
<<

The reason why your second series works, is because you are doing the Calculations *inside* the parenthises <sp> first.

You must take in order the compiler does your calculations....
parentheses are ALWAYS done first

Value = 3 + 4 * 5; Value = 35
Value = 3 + (4 * 5); Value = 27
Value = (3 + 4) * 5; Value = 35

Now working with integers...

Value = 3 + 4 / 5 + 6 Value= 7 if compiler reads left to right
Value = 3 + 4 / 5 + 6 Value= 10 if compiler does Multilplication ahead of addition
Value = (3 + 4) / (5+6) Value = 0


You must be careful on using parentheses and how a compiler computes values. I *always* use parantheses, so that I will force the compiler to calculate my values correctly... nomatter which order a compiler runs through complex calulations.

Dwayne