-2

I'm writing a simulator which uses US currency (pennies, nickels, dimes, quarters, and half-dollars). The implementation is something like this:

B = B_0;

While not done:
   B += simulate(strategy, investment);

I'd like to avoid floating-point while not having to make expensive checks for overflows (like B < INT_MAX). Is there a quick and accurate way to use integers-only here?

user1505713
  • 615
  • 5
  • 20
  • 2
    Your title asks one thing, but the body asks another. Are you asking how to perform integer addition without having to check for overflow? Or are you asking how to represent currency without using floating-point numbers? – Jonathon Reinhart Mar 19 '18 at 01:47
  • 2
    That doesn't look like C code. What is wrong with just expressing all prices in pennies, then when you finally display the result, convert to a Dolllars-n-Cents display? – abelenky Mar 19 '18 at 01:48

1 Answers1

0

If you're using GCC, you can use __builtin_add_overflow to perform quick addition with overflow check.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328