3 ms·
It is the programmers job to check for overflow. There are a lot of comments here about having a language check for overflow, but that is not practical. Specifi
by phkahler 12y ago
It is the programmers job to check for overflow. There are a lot of comments here about having a language check for overflow, but that is not practical. Specifically, the language doesn't know what to do in the case of overflow. The best it could possibly do is throw an exception, and I suppose that's what those commenters want it to do. But it's still up to the programmer to decide what to do and implement something. Are you going to do that for every math operation in a program? If not then you're already thinking about where potential problems may occur. Sometimes you want an overflow. I like to use 16 bit values to represent angles from 0 to 360 degrees - you can add and subtract these and never need to worry about the wraparound - I don't want that to throw an exception. If your code is going to overflow when you don't expect it to, you've got a bug and the language isn't going to be able to save you.
I feel like noobs hitting an overflow for the first time think the world would be better if the machine could "just take care of it".
That said, one solution to overflow in some cases is saturating arithmetic. Supported on some processors, but by no languages that I know of. That may be worth considering.
- aidenn0 12y agoSpot the signed integer overflow here that leads to undefined behavior on targets where "int" is 32-bits: uint32_t leToWord(uint8_t bytes) { return bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24; }
- detrino 12y agoThis is more about C's integer promotion rules than it is about overflow.