3 ms·
> ...especially since integer handling in C is so treacherous. I'm still learning C, having not had much reason to do so until recently, so I'm not quite sure
by korethr 9y ago
> ...especially since integer handling in C is so treacherous.
I'm still learning C, having not had much reason to do so until recently, so I'm not quite sure I understand this statement. How is integer handling in C treacherous (any more so than any other language, especially other languages that operate as close to the metal as C)? Is it something to do with signed vs unsigned, and beware of over/under-flow when doing math? Or is it a more insidious subtlety I'm ignorant of because it has been biding its time for a more perfect opportunity to bite me in the ass?
- tptacek 9y agoTwo bottles of beer on the wall, two bottles of beer. Take one down, pass it around, one bottle of beer on the wall. One bottle of beer on the wall, one bottle of beer. Take it down, pass it around, zero bottles of beer on the wall. Zero bottles of beer on the wall, zero bottles of beer. Take one down, pass it around, four billion, two hundred ninety-four million, nine hundred sixty-seven thousand, two hundred ninety-five bottles of beer on the wall. (Yes, you pretty much have it in your question; the Google search you want to make to learn more is [integer overflow]).
- zerokernel 9y agoAnd various undefined behaviours (signed overflow etc.) colluding against the programmer to the effect that compilers sometimes delete range-checking code. Integer promotion rules are not simple, either. Integer width rules, far from simple.
- dllthomas 9y agoOverflow of a signed integer - even in intermediate values - is technically undefined behavior, with the concomitant nasal demons, etc.
- Jtsummers 9y agoA bug in an early XCom game led to character's becoming so fast that they couldn't leave the landing zone. Stats were stored in an 8-bit field and were incremented at some (variable, depended on other factors) rate as the character leveled up. Once they hit 255 in a stat, the next time they leveled up their stat would be back to single digits. This sort of behavior is silent in C so you have to have bounds checking yourself to make sure you don't cause underflow/overflow. Also, be careful with enumerations. Any integer can be stored into the enumerated type and, at best, the compiler will warn you (an error if you use the right compiler flags) that you haven't cast it to the enumerated type. But nothing guarantees that it's actually in the range of the enumeration.
- mikestew 9y agoHere’s a lovely real-world example, discussed just recently here on HN: https://kotaku.com/why-gandhi-is-such-an-asshole-in-civilization-1653818245 https://kotaku.com/why-gandhi-is-such-an-asshole-in-civiliza... Unfortunately, most integer issues don’t have outcomes that are nearly that amusing.