3 ms·
> In some sense, the problem isn't that the compiler "can't" detect that an integer addition will overflow. It absolutely can't if it doesn't know what the val
by foxfluff 5y ago
> In some sense, the problem isn't that the compiler "can't" detect that an integer addition will overflow.
It absolutely can't if it doesn't know what the values are going to be.
> the compiler will have to flag every integer addition as UB
No, I disagree. If it has no knowledge of my runtime values, it can't flag addition as UB because it isn't. It's UB only if I'm using values that would overflow, and the compiler in general can't know that. If I've done my program right, it will never overflow. There is no UB, any flag would be just absolutely wrong. The compiler couldn't detect UB. There's nothing to flag.
If it knows the values, then of course it can detect it and flag it:
x.c:3:18: warning: integer overflow in expression of type ‘int’ results in ‘-2’ [-Woverflow]
3 | int a=2147483647+2147483647;
> Programmers do not, in general, want to do the amount of work it takes to safely add two numbers together.
I agree that overflow-checking is needlessly sucky in C but that's not "the problem." I usually make sure my arithmetic is safe but the compiler won't know it.