r/C_Programming • • 3h ago

Question How do you catch fixed-point overflow before it becomes a visible bug?

I’m working on some graphics code in C using fixed-point arithmetic. When something looks wrong, it can be hard to tell whether I’ve lost precision or an intermediate calculation has overflowed.

How do you check this while developing? I’m especially interested in catching the first bad calculation, before the result gets passed through several more steps.

AI helped word this question.

2 Upvotes

7 comments sorted by

2

u/pantalanaga11 2h ago

Range check your operands prior to any calculation that may overflow or underflow.

0

u/CAPTAINCAPSLOCK111 2h ago

Thanks. Catching it before the calculation is exactly what I want, rather than tracing a bad result backwards. Do you usually put those checks in shared arithmetic functions so you can stop in the debugger at the first failure?

AI helped word this reply.

2

u/tastygames_official 2h ago

how would you as a human do it? you need to check the operands before every operation to see if the resulting operation will overflow. There's no other way I can think of doing this.

0

u/CAPTAINCAPSLOCK111 2h ago

Thanks. I should have been clearer that I was asking how people organize those checks during debugging. The suggestions here about wrapping the arithmetic operations are helpful for that.

AI helped word this reply.

1

u/IchBinEinZwerg 1h ago

If you practice TDD, or at least write testable code, then you can check your code works within boundaries, to the right kind of precision etc, all with automated tests.

0

u/PMadLudwig 2h ago

If you used AI to word the question, AI could have given you the answer too.

If you are using C23, then there is a library called <stdckdint.h> (I haven't used it because it is recent, not even sure if my compiler supports it).

If you are using an earlier version, there will be compiler specific extensions that do the same thing, say __builtin_add_overflow in gcc/clang.

Both of these return a bool that you have to check after every calculation.

If you want to use standard C pre 23, then you need to check the arguments beforehand, which takes some care: if you want to check a+b where a and b are of type int (so signed), then testing (b>0 && a>INT_MAX-b) || (b<0 && a<INT_MIN-b) will check for overflow first, and you probably want to wrap that into functions for each operation, again, you need to test a bool each time.

1

u/CAPTAINCAPSLOCK111 2h ago

Thanks for spelling out the options, especially the pre-C23 approach. I was hoping to hear how people handle this in their own code, but I could have made the question more specific. Wrapping the checks per operation gives me a concrete starting point.

AI helped word this reply.