r/C_Programming • u/CAPTAINCAPSLOCK111 • 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
2
u/pantalanaga11 2h ago
Range check your operands prior to any calculation that may overflow or underflow.
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.
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.