4 ms·
An unsigned integer will never be negative, that intent is expressed clearly and correctly. What the operational semantics should be is unclear, because of the
by cle 5y ago
An unsigned integer will never be negative, that intent is expressed clearly and correctly. What the operational semantics should be is unclear, because of the tradeoffs involved in signaling an error.
In terms of the C standard, "3-4" for unsigned ints is modular arithmetic, and the "wrong thing" is assuming that it will do anything other than wrap around. This is very clearly defined, and implied whenever you see an arithmetic expression on unsigned integers.
- kazinator 5y agoConversion from signed to unsigned is implicit and silent. The expression being converted to your "can never be negative" type isn't nonnegative!!! Its value drastically changes; e.g. -3 becomes a huge number.
- snovv_crash 5y agoNot if you pass -Wconversion to GCC
- dagss 5y agoClearly defined, but very inconvenient and makes it too easy to write buggy code that looks correct on surface.
- cle 5y agoInconvenient to whom? It’s pretty inconvenient not to do that if you eg have strict memory/performance requirements. C made the right tradeoff IMO. You can protect yourself against overflow if you need to, but if it always signals errors you can’t turn that off.