5

Basic question: How far do I have to go to assure that integer math is done correctly? For example, this is probably overdone:

unsigned long burnTime = 0UL;
unsigned long curBurnTime = 0UL;
// Do some stuff that sets the above variables to millis() at various times
// Later on...
unsigned long adjustedBurnTime = (unsigned long) ((burnTime + curBurnTime) / 1000UL);

Would the math be done correctly if I went to a more minimal last statement (since all the elements of the equation are unsigned longs)? Like this:

unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000UL);

Or even:

unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000);
bluesmoke
  • 53
  • 5

1 Answers1

3

Any good C manual will tell you the result type for each basic math operation on given types. But briefly, the basic math operators return a result as wide as the widest operand, with the narrower operand being widened to match the wider one, if they differ. The same with assignment: assigning a result of a given type to a variable of the same type will not involve any conversion.

tl;dr: No, you're not missing anything. You don't need any casts in your example.

PS: One thing you do need to be aware of is whether any of your intermediate results will overflow the arithmetic type you're using. For example, the final result may be not exceed an unsigned long but the expressions (burnTime + curBurnTime) must also not exceed it. This is a greater concern with smaller data-types, of course.

PPS: Good on you for tackling fixed point arithmetic rather than just reaching for the floating-point library!

JRobert
  • 15,407
  • 3
  • 24
  • 51