Settings

Theme

Ask HN: Why C happily allows numeric overflows instead of returning carry bit

3 points by InterNautic 3 years ago · 5 comments · 1 min read


It always been amazing me how simple solution it would be and hardware compliant pretty much on every CPU platform in existence. But for some strange reason carry get totally ignored in language design.

dswilkerson 3 years ago

It is not really C, it is the underlying hardware. C is just portable assembly language.

If I recall correctly, MIPS64 would fault on integer overflow, but I did not find a reference saying that after a quick search.

The RISC-V team at Berkeley took this feature out.

The famous example among software correctness people is the lack of detecting integer overflow leading to the Ariane 5 rocket disaster, although this seems to have perhaps been more complex than just an integer overflow:

https://www.bugsnag.com/blog/bug-day-ariane-5-disaster

What went wrong?

The fault was quickly identified as a software bug in the rocket’s Inertial Reference System. The rocket used this system to determine whether it was pointing up or down, which is formally known as the horizontal bias, or informally as a BH value. This value was represented by a 64-bit floating variable, which was perfectly adequate.

However, problems began to occur when the software attempted to stuff this 64-bit variable, which can represent billions of potential values, into a 16-bit integer, which can only represent 65,535 potential values. For the first few seconds of flight, the rocket’s acceleration was low, so the conversion between these two values was successful. However, as the rocket’s velocity increased, the 64-bit variable exceeded 65k, and became too large to fit in a 16-bit variable. It was at this point that the processor encountered an operand error, and populated the BH variable with a diagnostic value.

  • ttyprintk 3 years ago

    Excellent. To answer OPs question: on some hardware, you cannot distinguish between an overflow and some other fault. On systems without this limitation, you might include a model-specific header and look at a particular bit in flags to find the carry. I presume there are architectures, maybe with a math coprocessor, where nabbing those flags requires an interrupt.

    Asking the language to define math around each of those is actually less portable.

snvzz 3 years ago

Nothing is stopping you from doing a manual check for overflow.

And nothing is stopping the compiler from leveraging flags, in architectures that have them (e.g. RISC-V does not).

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection