18 ms·
Almost Always Unsigned
- Flocular 5y agoWhat fans of unsigned integers seem to really want is array access in the form of x[i %mod% LEN]. While signed integers "kind of" give you an error on overflow (Except your unlucky or somebody was malicious). Is there a way to combine both? As in give me an error on overflow for "debug builds" and always mod-LEN on "release builds"?
- jcelerier 5y agoUnsigned does not mean "not negative", it means "modular arithmetic". The only few cases you want that are e.g. hash functions, crypto, etc. In all the other cases it's a mistake, and the "patterns" shown in this article to circumvent the issues with unsigned just for the sake of using it are extremely ridiculous I think and much less readable than the normal code using signed integers. If you have things that must never be negative, define a type that does that and gives an error (there are many good safe_int examples in C++) whenever an operation gives a negative number as in that case you've already lost and your business logic / input filtering / .... is wrong and needs to be fixed. Anecdotally, I've written a few hundred thousand kloc of c++ so far and I've never ever had a bug due to signed overflow. Unsigned underflow OTOH... I'm just thankful for clang's ubsan to warn on it because of how many issues it caught. For the immense majority of programs you'll never have sizes close to 63 bits anyways since the CPUs we use barely have 52-bits of address space at most (and if you have more you're likely already using 128 bit sizes) > Where unsigned does benefit here is when these are used as indices into an array. The signed behavior will almost certainly produce invalid indices which leads to memory unsafety issues. The unsigned way will never do that, it’ll stay bounded, even if the index it produces is actually wrong. I'd take negative indice over silently wrong indice any day of the week. The first will be caught hyper quickly, the second will send money to the wrong account silently for a couple years before anyone notices and then you're in much deeper issues.
- CasperDern 5y ago> Unsigned does not mean "not negative", it means "modular arithmetic". Unsigned does mean non-negative (or rather no indication of negatives) as the sign of a number is just the positive or negative factor of a number: 1 or -1.
- hamburglar 5y agoThe suggestion of using an unsigned loop counter starting at size-1 and decrementing until “i<size” is no longer true starts this article off with a “this is bad advice” flavor to it in my book. If I encountered that code I’d stare at it way longer than necessary because I’d be trying to figure out what cleverness is hidden in the bizarre/backwards way the loop continuation test is written. I don’t know why you’d do this to someone else who has to read your code.
- reallybigballs 5y agoreverse iteration seems pretty basic …
- xxs 5y agoIt's an idiom - obviously very little known, likely less known than comparing floats to themselves being a NaN check. The standard idiom for doing a reverse loop would be: "for (int i = size; i-- > 0; ) ...". As a side benefit it has lower registry pressure. Some folks have issues reading that one as well. Saying all that not being 'unsigned fan', just the popularity of the idioms comes with their use frequency, and given that 'unsigned; is not popular at all...
- AnotherGoodName 5y ago>Unsigned does not mean "not negative", it means "modular arithmetic". Signed is modular arithmetic with an offset. An unsigned char called i can be thought of as "i mod 256" A signed char called i can be thought of as "((i+128) mod 256) - 128" All results for over/underflow hold for 'i' cast into a char if you do the above in both cases. I think the premise of the article is quite reasonable. It's slightly easier to reason about over/underflow for unsigned arithmetic since it's not offset.
- jcelerier 5y ago> Signed is modular arithmetic with an offset. it is not, it models integers (Z). The model only works in the bounds of what the platform can offer of course ; when you use "int" you say "this is an integer. In any case I'm supposed to encounter, adding two positive integers will yield a greater positive integer ; if I add numbers so big that my platform cannot represent the sum my program is meaningless anyways". It is very unlike unsigned which models (much more accurately since it's much easier for our computers with finite memory) Z/pZ.
- AnotherGoodName 5y agoSigned and unsigned are actually treated internally the same on computers. The reason you see -2 printed out when you add signed chars -1 and -1 together is because adding 255 and 255 together gives 254 under mod 256. The signed model that allows negative numbers relies on the fact that all numbers on computers are modular arithmetic. So in that sense any argument that unsigned is modular and signed isn't is incorrect. You're better off choosing the one that forces you to consider how the computer actually operates under the hood.
- jcelerier 5y ago> Signed and unsigned are actually treated internally the same on computers. if you are writing code in C or C++ the computer you are programming for is the C / C++ abstract machine. C++ recently sanctified complement-of-two as integer representation, but C does not and supports machines with one's complement representation.
- ghusbands 5y ago> Unsigned does not mean "not negative", it means "modular arithmetic". In which case it has a terrible name. The name clearly indicates that the primary feature is that it is not signed, and the logical conclusion from that is that it is not negative. That said, I agree; using signed types in C/C++ does generally seem safer and a majority of the techniques listed in the article are unsafe, logically confused, and/or inhibit optimisation. Using signed types in languages like C# is also generally more pleasant, because otherwise you end up with a lot of casts just to interact with the base types (like arrays), language features and third-party libraries.
- Noughmad 5y ago> The name clearly indicates that the primary feature is that it is not signed, and the logical conclusion from that is that it is not negative. No, the logical conclusion is that since it has no sign, you don't know whether it's positive or negative. Otherwise the name would be "positive" or "non-negative", not "unsigned". And this conclusion would also be correct.
- xxs 5y ago>The name clearly indicates that the primary feature is that it is not signed, and the logical conclusion from that is that it is not negative. Years ago, when the names were designated the CPUs didn't even have proper signed instructions. There was a sign flag, and that was all. In that regard the unsigned was the natural CPU sympathetic type.
- int_19h 5y agoAnd yet the default type for variables and function arguments in C was (before it got deprecated) signed int, not unsigned.
- xxs 5y agosigned/unsigned stuff predates C, though. My (lack of) experience with C came much later, when I had used assembly for 3 different CPUs already, so no recollection of the times.
- virtualritz 5y ago> Unsigned does not mean "not negative", it means "modular arithmetic". It does mean "not negative" in languages with bounds checks. Like Rust.
- whattheactualf3 5y agoIs it called "unsigned" though? In Racket (and in mathematics) we call those natural numbers. The very notion of "unsigned" was invented by video game programmers at Bell Labs. In mathematics positive numbers are still signed (they just have a positive sign).
- gumby 5y ago> The very notion of "unsigned" was invented by video game programmers at Bell Labs. PL/I had (has) unsigned integers back in the 60s, picking up the idea from earlier languages. I believe the novel datatype in PL/I was the CHARACTER type; into the 80s I was still programming machines with variable length bytes. In many ways PL/I heralded the current Ordovician stage of programming languages, with the enormous Cambrian flourishing of hardware-specific (and company-specific) languages slowly dying out. Interestingly the only surviving languages older than it, FORTRAN and LISP, are also machine-independent.
- masklinn 5y ago> Is it called "unsigned" though? Yes: https://doc.rust-lang.org/std/primitive.usize.html https://doc.rust-lang.org/std/primitive.usize.html > The pointer-sized unsigned integer type. > In Racket (and in mathematics) we call those natural numbers. Naturals have no upper bound. Most languages don't have naturals, because they do have upper bounds. Languages which do provide naturals (limited by the host machine) usually don't bother with signing segregation, and give you mathematical integers (again limited by the host machine's capabilities).
- ncmncm 5y agoUnsigned types are supported in machine language. Any language that offers access to features of the machine will support unsigned numeric types. No language supports natural numbers. The best you can get is bignums. A language that calls its numbers natural is just lying. (Likewise, integers, and reals.) "int" is not a lie, it is a hint.
- quelsolaar 5y agoInteresting perspective. I dont have the same experience. To me a wraping 32 bit index on a 64bit machine is much more likely to seg fault if it reads 4 billion values forward, rather than a few bytes backwards and therefore i find unsigned index wrapps to be easier to debug. In all fairness wrapping indicies are an extremely rare bug for me, so i cant say i have much experience debugging it.
- jcelerier 5y ago> In all fairness wrapping indicies are an extremely rare bug for me, so i cant say i have much experience debugging it. Do you run your code with -fsanitize=undefined -fsanitize=integer ?
- quelsolaar 5y agoNo I do not. I run ISO conformant C without options.
- jcelerier 5y agoYou really should try it on your codebase if you have the occasion
- eterevsky 5y agoI think when you use a variable that can have values in the range of millions, it's prudent to use 64-bit types and not 32-bit unless you are very much memory-constrained. And I've never seen a 64-bit signed variable overflow.
- kazinator 5y agoUnsigned means "modular arithmetic with a modulus that you do not choose and that is implementation-defined unless you have pinned down the bit width of the unsigned type, and that has implicit conversions from signed types that drastically alter the value". Note that when mathematicians work in the area of congruences, they do not use unsigned integers. For instance, when we look at Euler's Theorem: https://en.wikipedia.org/wiki/Euler%27s_theorem https://en.wikipedia.org/wiki/Euler%27s_theorem all the quantities in the formula can be understood as just integers, not unsigned integers. The exponentiation of a can be understood as regular exponentiation. The modularity plays out in the triple-equal-sign operator and the (mod n) parenthetical part which says that the two sides of the equation are equivalent in a particular way. The left side of the equation uses ordinary exponentiation and can produce values >= n; it is not wrapped. It's crystal clear that we cannot replace the triple equal sign with the regular one, and drop the (mod n).
- SAI_Peregrinus 5y agoThey also don't use signed integers, in the sense that computer languages use the term. Signed integers are also bounded in extent, and for most systems wrap on over/underflow. Euler's Theorem doesn't hold for them any more than it does for unsigned integers. Don't treat computer "integers" like mathematical integers. It leads to pain. They're members of a few finite fields.
- flohofwoe 5y agoI'm in the "almost always signed camp" - at least in languages without robust over-/underflow checking. But I sometimes wonder if it would have been better to not carry the 'signedness' in the variable type in high level languages, but instead treat integer variables as 'signless' bags of bits, and signed-vs-unsigned are just different views on those bags of bits, just as in assembly. Most operations on two's-complement numbers result in the exact same bit pattern, no matter if the involved operands were 'signed' or 'unsigned', and the signedness only matters when printing the result, or for explicitely extending the sign bit when casting to a wider type.
- spc476 5y agoBecause when C was standardized in 1989, there were a few vendors that wanted to support non-two's-complement hardware, and C has been stuck with that ever since. But more to the point, even on two's-complement hardware, the CMP instruction doesn't care about the signedness, but it typically sets flags (for those CPUs that have flags) for both signed and unsigned results, and there are different conditional branches one can take for less-than, less-or-equal, greater-or-equal, and greater-than.
- flohofwoe 5y agoI often wished I had access to the flag bits in C (or at least a somewhat portable subset). Would be very handy for writing CPU emulators :)
- spc476 5y agoHaving written a CPU emulator [1], I don't thunk it would have been of much use. The Intel CPUs typically don't set the flags on a MOV, but Motorola CPUs typically do. [1] https://github.com/spc476/mc6809 https://github.com/spc476/mc6809
- quelsolaar 5y agoI agree with this almost entierly and i use almost exclsivly unsigned ints in C. However, its not true that unsigned is faster because the compiler can optimize. Consider: x = (x * 2) / 2; If x is unsigned, and overflows, x will not be the same after this operation so the compiler can not optimize away this line. If x is signed and overflow is undefined, the compiler can assume it wont overflow and optimize away the line. UB affords the compiler a lot of optimizations.
- MaxBarraclough 5y agoThe article acknowledges this: > There are some optimizations compilers can make assuming signed integers cannot underflow or overflow that unsigned does not get to participate in.
- Const-me 5y ago> its not true that unsigned is faster because the compiler can optimize. It’s not false either. For instance, casting int32_t into int64_t requires an instruction like movsxd which does sign extend. Casting uint32_t into uint64_t can often be merged into the instruction who computed the uint32_t value, because the instruction which write 4 bytes registers like eax zero out old data in the higher 4 bytes of the corresponding 8 bytes rax register.
- quelsolaar 5y agoThanks! I didn't know that!
- virtualritz 5y agoWhile wrapping parts of OpenSubdiv for Rust [1] I noticed the C++ API was littered with uses of int for indexing/lengths (both are always positive) of geometry buffers. So I opened a ticket with Pixar [2]. Some of the same strange arguments were brought forward (incl. the Google style guide BS). I wrote a longish reply [3] that mentions two comments [4,5] from an ill-guided article promoting use of signed in C++. I closed the ticket in the end because I felt that if people really believe there are good reasons for signed in the cases at hand they haven't grokked the problem sufficiently – trying to convince them otherwise would not be a good use of my time. [1] https://crates.io/crates/opensubdiv-petite https://crates.io/crates/opensubdiv-petite [2] https://github.com/PixarAnimationStudios/OpenSubdiv/issues/1222 https://github.com/PixarAnimationStudios/OpenSubdiv/issues/1... [3] https://github.com/PixarAnimationStudios/OpenSubdiv/issues/1222#issuecomment-814548396 https://github.com/PixarAnimationStudios/OpenSubdiv/issues/1... [4] https://www.learncpp.com/cpp-tutorial/unsigned-integers-and-why-to-avoid-them/#comment-487024 https://www.learncpp.com/cpp-tutorial/unsigned-integers-and-... [5] https://www.learncpp.com/cpp-tutorial/unsigned-integers-and-why-to-avoid-them/comment-page-2/#comment-474548 https://www.learncpp.com/cpp-tutorial/unsigned-integers-and-...
- jcelerier 5y agoQuoting one of these comments: > The argument with substracting 5 from 3 is not an argument against using unsigned. When you use signed you can run into a similar problem when the result underflows. This happens much less frequent and causes UB, at INT_MIN, which is the worst kind of bug. The bug is often not triggered durring testing and you will only notice it when it is too late. The "When you use signed you can run into a similar problem" part is just not true in our world. 3 - 5 happens much more often than anything that may cause signed .*flow. "signed underflow" "bug report" yields 8 results on google FFS
- leni536 5y agoNo such thing as "underflow" for integers. Signed integers overflow in both directions. Underflow is a floating point concept. Edit: https://en.m.wikipedia.org/wiki/Arithmetic_underflow https://en.m.wikipedia.org/wiki/Arithmetic_underflow
- kstenerud 5y agoI've vascillated between one camp and the other over the years, but in 25 years of professional development, other than pointer arithmetic I can't think of a single time where I've dealt with numbers that exceed a trillion in either direction. Integer overflows are so rare that I can't even remember one happening with 64-bit values. Underflow on the other hand... I've encountered that plenty. I'm now back in the signed camp. Signed integers make it a lot easier to sanity check integer subtraction when negative values are disallowed (a common situation), and it's easy to reason about. Also, not converting between signed and unsigned avoids accidental conversion overflows due to different expectations, so keeping it signed bypasses that whole can of worms while maintaining maximum flexibility. Unsigned gives you 2x the positive numeric range, which 99.999% of the time you'll never use (and if you did, underflow detection would become a nightmare). I can't think of a single time I've heard someone complain "I wish Java's long type supported up to 16 quintillion instead of a paltry 8 quintillion" At the end of the day, code is for people, so keep it easy for people.
- cma 5y ago> I can't think of a single time where I've dealt with numbers that exceed a trillion in either direction. A big one is dealing with currencies like Japanese yen in financial software.
- kstenerud 5y agoAbsolutely! But how about a quintillion? Signed 64-bit integers give you 8 quintillion in the positive integer space, and unsigned gives 16 quintillion. The question is: Will the difference between 8 and 16 quintillion matter enough to say "unsigned by default"? But currency types need to be signed anyway, so I guess that's that ;-)
- virtualritz 5y agoI think types should express intend. This adds more 'value' to the code for people than allowing them to switch their brains off because something is 'unlikely' to happen. A large class of bugs exists because people assume stuff is unlikely. I also think one has to distinguish between API and actual code. If you write a lib that takes inputs that should never be negative you can express this without writing a single line of documentation about it (or if you do, requiring the user to read it) by using unsigned types in these places. You can still use signed types in your actual library code if you want/must/believe in that but do not pollute the outside API with them if unnecessary.
- iddan 5y agoI would have really loved to have different number types in JavaScript and to be able to define them with TypeScript. Not from the performance perspective (like different sizes) but integer vs float and unsigned vs signed can be really useful
- Slartie 5y agoThe one thing I really, really hate Java for is its lack of unsigned integers (there are a lot of other minor inconveniences, like in any language, but nothing comes close to the missing unsigned types). This of course has to do with me frequently writing and maintaining low-level hardware and network protocol code, talking to devices on the other end that had firmware written in C and therefore expect you to be fluent in bit manipulation. But hey, all that nice software is useless if it can't eventually interface with the real world out there, so hardware will stay relevant and necessary and the accompanying close-to-the-metal code can't be optimized out of the system, hence I consider good tools for doing bit-level work an important quality in any general-purpose programming language. And besides bit-level operators that means support for unsigned integers which are needed to easily combine bit-level with classic arithmetic operations. You can actually live without either of these in practice and still do low-level stuff, but it is very unintuitive, has poor runtime performance and leads to hard-to-read and bug-prone code.
- matsemann 5y agoWhile Java doesn't have unsigned types, it at least with java8 got functions to operate on ints as if they were unsigned. But Kotlin (also running on the jvm) got unsigned types with built in operator overloading for them, making it easy to work with. "val a = 100u" gives you an unsigned Int. If you use Java, there are few reasons not to use Kotlin. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-u-int/ https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-u-int/
- hashmash 5y ago> has poor runtime performance Are you referring to performance issues caused by lack of unsigned types? Do you have a specific example? Based on my observations, the conversions necessary for acting on signed types as if they were unsigned generates the correct machine instructions designed for unsigned types.
- leni536 5y ago> Of course this is dangerous as it’s a narrowing conversion, with a cast which silences a legitimate warning. In C and C++ it invokes undefined behavior when given specific large values and most certainly is exploitable. Most applications would just crash on inputs >= 0x7ffffffffffffffff. No, it's not. Overflow on arithmetic is undefined, but on conversion it's implementation defined. In C++20 it's defined.
- CJefferson 5y agoI really donnt buy it is a "trivial idiom" to check unsigned undeflowing by writing 'i > size'. I'd have to check that was right all the time. Also in general saying all we have to do is (I'm paraphrasing a bit) "not make mistakes" is, to me, a bad idea, as all programmers make mistakes. I sometimes assert after a calculation that a value is >= 0, it's much harder to check that if it's underflowed because it was unsigned.
- tialaramex 5y ago> this concept applies to all languages, regardless of their choices No it doesn't. Neither signed nor unsigned integers in WUFFS permit overflow or underflow, at runtime the integers behave the way you were taught in school. Adding two positive numbers together always results in another positive number, because duh. WUFFS catches all the cases this programmer worries about at compile time and insists you fix them. One of the first examples WUFFS presents you is what if we take this correct code for a well known operation and we tweak it so that it can overflow. The compiler rejects the modified code, pointing out that it could now overflow and so isn't valid WUFFS. Now, WUFFS is a special purpose language, you can't rewrite your 5MLOC C++ system in WUFFS. But then again, this shouldn't make you feel glad (because C++ is so powerful) but instead sad (because C++ can't offer you this valuable defence against your own stupidity). It should also make you determined to use WUFFS everywhere you possibly could, although doubtless it won't.
- Slartie 5y agoTangentially related: https://docs.microsoft.com/en-us/answers/questions/680467/exchange-scan-engine-failed-to-load-can39t-convert.html https://docs.microsoft.com/en-us/answers/questions/680467/ex... Had Microsoft used an unsigned int to store the date - which can't ever be negative in this notation - Exchange wouldn't have stopped working worldwide on 1/1/2022. They would have been safe for another two decades, in which they would hopefully had either gotten rid of that weird code or switched it over to 64 bits.
- sparkie 5y agoHad Microsoft used common sense, they would not store the string representation of a date as an integer, period.
- jeroenhd 5y agoIt depends on the use case. If this is an index that's commonly sorted by and enumerated, the performance impact of a string compare versus a simple 64 bit integer compare would be enormous. A single compare instruction versus a series of unicode character comparison operations with subsequent jump instructions would not only be more code, it would also be more likely to wreck the branch predictor of the CPU with all the added conditionals. I think using 64 bit integers for their natural hardware-accelerated sortability is quite a neat trick. You just have to be sure to use actual 64 bit numbers, and you have to think ahead to check if your data type is wide enough to actually contain your data.
- masklinn 5y ago> They would have been safe for another two decades, in which they would hopefully had either gotten rid of that weird code or switched it over to 64 bits. Why? The code would have kept working all along, there would have been no reason to explore it, and lots of other issues to chase.
- bee_rider 5y agoThis ought to be the canonical example for this sort of thing -- in the sense the unsigned value only* 'helps' if you are already doing something terminally silly. *to some definition of 'only' that excludes the cases like cryptography, hardware, etc stuff.
- MaxBarraclough 5y ago> almost all code that uses signed integers to represent values that will never be negative, tends to have a cacophony of range assertions and other tests which are just as error-prone as bounds checking to remembering to write, but also maintain when refactoring. It’s truly underappreciated how much those tests can be eliminated if your integer can never actually become negative due to the type system itself. This is something the Ada language gets right: you define your integer type with a range, and the compiler automagically inserts the runtime range checks. (Unless you switch them off with compiler directives.) It makes far more sense to bake the range-checks into the type than to do it the manual way and just hope you don't miss anything. You can do this in C++ using a library (thanks to templates) [0] but this is very rarely done. [0] https://www.boost.org/doc/libs/1_78_0/libs/safe_numerics/doc/html/safe_range.html https://www.boost.org/doc/libs/1_78_0/libs/safe_numerics/doc...
- lifthrasiir 5y agoRange types are not a panacea, especially combined with other arithmetic operators. There are essentially two options: [lo1, hi1) + [lo2, hi2) can result in a new type [lo1 + lo2, hi1 + hi2) and so on, or any operation reverts back to the base type. Only the former provides a static type guarantee but can be extremely annoying to use and you eventually have to constrain the type back with runtime checks. (Interval arithmetic also shares this problem.) Probably for this reason, to my knowledge, both Pascal and Ada implements the latter, which is more usable but also arguably useless: if your intermediate type is ranged you have to manually calculate correct bounds (a failure to do so will cause a runtime error), and if it's unranged there is zero guarantee even in the run time.
- MaxBarraclough 5y agoSomewhat related: there's apparently a defect in the Ada language spec which permits reordering of arithmetic operations such that out-of-range behaviour may hinge on the compiler's whim: [0] > non-parenthesized arithmetic operations could be re-ordered by the compiler, which may result in a failing computation (due to overflow checking) becoming a successful one, and vice-versa. By default, GNATprove evaluates all expressions left-to-right, like GNAT. Presumably one solution would be to use a three-address-code style [2] to completely tie the compiler's hands regarding ordering, but this seems painfully restrictive even by the standards of SPARK. Also, an Ada compiler's internal choice of base type (with which to implement a range-based integer type) can impact overflow behaviour: [1] > The choice of base types influences in which cases intermediate overflows may be raised during computation. The choice made in GNATprove is the strictest one among existing compilers, as far as we know, which ensures that GNATprove’s analysis detects a superset of the overflows that may occur at run time. I don't know if there's a fully portable robust answer to this second problem. (I believe you can generally use hints to force the Ada compiler to use a particular sized type, along the lines of C's uint32_t, but that this isn't portable.) edit On second thought, I imagine using a three-address-code style would solve this too. Either the result falls within the permitted range of the destination variable, or it doesn't. [0] https://docs.adacore.com/spark2014-docs/html/ug/en/appendix/portability_issues.html#parenthesized-arithmetic-operations https://docs.adacore.com/spark2014-docs/html/ug/en/appendix/... [1] https://docs.adacore.com/spark2014-docs/html/ug/en/appendix/portability_issues.html#base-type-of-user-defined-integer-types https://docs.adacore.com/spark2014-docs/html/ug/en/appendix/... [2] https://en.wikipedia.org/wiki/Three-address_code https://en.wikipedia.org/wiki/Three-address_code
- monsecchris 5y agoSigned integer overflow causing undefined behaviour allows the compiler to make significantly better optimisations. Here is Chandler Carruth, and clang developer, talking about it: https://www.youtube.com/watch?v=yG1OZ69H_-o&t=2356s&ab_channel=CppCon https://www.youtube.com/watch?v=yG1OZ69H_-o&t=2356s&ab_chann...
- munch117 5y agoThe reason I've always preferred unsigned is that it's easier to write code that is correct for the full input domain. Consider for example: extern void g(int); void f(int x, int y) { g(x - y); } The function f obviously doesn't work for all values of x and y: Some values will overflow, some values will underflow. How do you fix that? Writing an explicit check for whether x-y overflows is highly impractical, no one does that. Or you could document the limitation using pre- and postconditions that narrow down the range of allowed values to something you know will work: extern void g(int); void f(int x, int y) /* PRECONDITION: -1000000 <= x <= 1000000 and -1000000 <= y <= 1000000 */ { g(x - y); } No one does that either. I don't know why. There's no principled reason why you couldn't meticulously keep track of signed int input and output ranges. But that's how it is, no one does it, valid int ranges are always unstated. Now for the unsigned version of the same problem: extern void g1(unsigned); extern void g2(unsigned); void f(unsigned x, unsigned y) { if(x >= y) g1(x - y); else g2(y - x); } Assuming g1 and g2 are well-defined for all unsigned inputs, so is f. That was easy. It may look like more code, because there are two g functions now. But chances are you probably need to treat the x<y case differently somewhere anyway; in the larger scheme of things, unsigned is not more code.
- clappski 5y agoWhat you should be doing for checked arithmetic with GCC is use the builtins for those that aren’t aware; https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins...
- munch117 5y agoIt would be nice to see something like that standardised so you could use it in portable code. It doesn't solve the problem though. You still need to write some code for what to do if there's an overflow, and you need separate handling for underflow. So the signed case is now: extern void g1(int); extern void g2(int); extern void g3(int); void f(int x, int y) { int x_minus_y; if(__builtin_ssubl_overflow(x, y, &x_minus_y)) g1(x_minus_y); else if(x > y) g2(...); /* overflow */ else g3(...); /* underflow */ } Work in progress. I've given up on figuring out what arguments to pass to g2 and g3. Since the difference won't fit in an int, you would need to offset-adjust the value somehow in order to fit it in an int. Seems messy. Maybe you can think of something simpler.
- halayli 5y agoWhat's more important than preaching about signed vs unsigned is raising awareness not to use both. Most signed/unsigned related bugs (outside numerical/math sensitive domain) are due to using both simultaneously and the side effect is of course going to be overflow/underflow. On the other hand, I'd favor int over unsigned as it's more practical when dealing with memory address arithmetic & array indices due to address difference being signed.
- thrower123 5y agoUnfortunately if I were to try to use unsigned ints extensively, I'd be casting them back and forth constantly, because nearly every standard library function that I'd want to use expects int inputs or outputs ints. A small improvement in correctness is washed out by a huge decrease in ergonomics.
- ridiculous_fish 5y agoWhich standard library?
- ncmncm 5y agoYou do know that signed and unsigned ints convert implicitly, without casts?
- heisenbit 5y ago> for (size_t i = size - 1; i < size; i--) { Am I alone here feeling that this while working is anything but intuitive and is asking for trouble down the road? Just imagine having to change the countdown for whatever reason in maintenance to 1 instead of zero and you suddenly fiddle with the operator.
- throwaway744678 5y agoYou are not alone! This is completely unclear: the next guy reading your code will definitely "fix" the halting condition. I'd either handle i == 0 outside of the loop, or use something like: for (size_t j = size; j > 0; --j) { size_t i = j - 1; // etc. Or even: for (size_t j = 0; j <= size; ++j) { size_t i = size - j; // etc.
- whattheactualf3 5y agoThe argument is really strange. It says that unsigned ints can't become negative and it's a good thing. But they do that by instead having crazy high values. How is that a win? You could argue that it doesn't matter because an incorrect program is incorrect regardless. True. At least with signed integers you can represent differences between positive values. How do you do that with unsigned?
- ridiculous_fish 5y agoSigned integers may also have crazy high values so you're already on the hook for dealing with those. The case for unsigned values is that it frees you from having to think about negative inputs. We all know to check for divide by zero; how many remember to check for INT_MIN / -1? Regarding differences, in practice you usually want those differences to be non-negative. With uints, you compare first. Not: int length = end - begin; if (length < 0) return error; but: if (begin > end) return error; unsigned length = end - begin; This is also a good habit for signed ints, since it avoids underflow in more (but not all) cases. An old post with a few fun crashes for negative inputs: https://kqueue.org/blog/2012/12/31/idiv-dos/ https://kqueue.org/blog/2012/12/31/idiv-dos/
- happyweasel 5y agoMight be of interest: https://www.youtube.com/watch?v=Puio5dly9N8&t=587s https://www.youtube.com/watch?v=Puio5dly9N8&t=587s IMHO bjarne's comment sums it up nicely ... "Use ints until you have a reason not to. Don't use unsigned unless you are fiddling with bit patterns, and never mix signed and unsigned.."
- garaetjjte 5y agoEh, but C++ std likes to use unsigned size_t for sizes...
- croes 5y agoWouldn't it be better to write for (size_t i = size; i > 0; i--) { // ... } and use i-1 inside the loop instead of using underflow?
- xxs 5y agoor: "for (size_t i = size; i-- > 0;){...}"
- desdiv 5y agoI foresee two problems with that: Problem 1: If i is used multiple times inside the loop, then you might need to make a temporary variable for it, making it confusing: for (size_t i_plus_one = size; i_plus_one > 0; i_plus_one--) { size_t i = i_plus_one - 1; f(i); g(i); h(i); ... (The alternative is a bunch of i-1 all over the place, which is also confusing.) Problem 2: If operations inside the loop is short, then the extra "i-1" arithmetic could result in unacceptable performance penalties.
- hirako2000 5y agoI thought given the title that it was going to be tips and list of services to make accountless web use.
- upofadown 5y agoThis is an artifact of typing. Is your 16 bit value all ones? Then it might represent -1 or 65535 depending on what you believe the type to be. Perhaps it represents some sort of colour instead. When working in an untyped environment, this sort of question doesn't come up. If the value is intrinsically unsigned then that is what you and hence the program assume those bits mean. If the value is intrinsically signed then that is your illusion. Any ideas about overflow are entirely in your mind. You tend to see techniques used in an untyped environment that would never occur to anyone in a signed environment. It's all just bits.
- atq2119 5y agoSlight nitpick: > Here’s a somewhat non-exhaustive list of all the undefined behavior of signed integer arithmetic in LLVM which applies to all languages which use LLVM: > [... division examples ...] > INT_MAX - INT_MIN That's not true: 'sub i32 INT_MAX, INT_MIN' is defined perfectly fine in LLVM in the (modular arithmetic) way you'd expect as long as the 'nsw' (no signed wrap) flag isn't set on the instruction. For the most part, LLVM IR by default doesn't care about the signedness of values, integer types are just treated as a bunch of bits with modular twos complement arithmetic. Exceptions to this rule are explicit, e.g. the mentioned nsw flag (and there's also nuw for "no unsigned wrap"). The division examples are correct because if you want a signed divide, you have to explicitly encode it as a signed divide instruction in LLVM IR, which has the listed undefined behaviors baked in.
- Asooka 5y agoThe author makes good points, but the takeaway I get is that signed under/overflow should always be defined, maybe in a platform specific way. The one good argument for leaving it undefined was for better loop optimisation, but if we're going to use unsigned for loops, then what's the point.
- the__alchemist 5y agoChoose the right tool for the job. Examples: - Loop using an iterator: unsigned pointer size - Array index: unsigned pointer size - Enum used to represent a register value that's 8 bits or less: unsigned 8 bit - ... used to represent a register value that's up to 16 or 32 bits: unsigned 16 or 32 bit number - Integer value that could be negative: Signed, with the appropriate size - Doing numerical operations and you have an FPU: Float. Unless you're careful, you know what you're doing, and it's either performance critical or you're using dedicated a dedicated fixed-pointer hardware peiph... then maybe fixed point with a signed or unsigned integer. - Analog value that can only be positive; maybe a voltage: unsigned integer according to precision of the ADC etc - Analog value that can be positive or negative; maybe pH, audio, or something using a differential ADC: signed integer - Performing mathematical operations including subtraction, don't expect fixed-point errors to come up, and you don't want to use floating point or don't have an FPU: signed integer
- pornel 5y ago> It’s very trivial to check if x * y would overflow though and you should just learn the extremely simple and obvious test. if (y && x > (T)-1/y) I think it's sarcasm, but with C guides like this it's never certain :)
- ufo 5y agoMaybe this is not a problem for calculating the size of a memory allocation, but that division operation is going to be several times slower than the multiplication it is guarding. Is there a faster way to check for overflow, perhaps using compiler builtins?
- saberience 5y agoMaybe I'm just a moron but what makes this test "obvious"? What is T?
- afiori 5y agoi imagine it is the type of x and y
- ajuc 5y ago> delta = abs(x - y); > The argument is that unsigned is dangerous here because if y > x then you get underflow. The problem with this argument is it’s not valid because the code itself is simply incorrect regardless of the signedness of x and y. There are values for both x and y which will lead to signed integer underflow. So like before, in languages like C and C++, you just unconditionally invoked undefined behavior since signed integer underflow is undefined. Yeah because x=1, y=2 is just as likely an input as x=MIN_SIGNED_INT, y=1.
- jy14898 5y agoThe argument that most signed integers never use the negatives is a bit misleading, as I'm sure most unsigned integers never use the upper half of their range either
- graphitemaster 5y agoAuthor here. I believe many of the complaints here are concerned about what is more common rather than what is universally better over all possible inputs which is actually the point of view this article is written from. The issue with the "general case" is that exploits are never actually found there, they're always found in the edge cases such as large, or "pathological" values as it were. Signed integer arithmetic has more of these edge cases than unsigned when it comes to sizes, indices, and offsets used in expressions controlling memory (either directly, or indirectly) which is the most common application of integers in a codebase. The native-word-size unsigned integer type covers the full numeric range for those operations, while signed simply cannot. At the same time, preventing a whole numeric-range that is simply incompatible with those operations (negative values), and a whole class of issues related to undefined operations. The only real edge-case unsigned has that is more error-prone is values close to zero under subtraction and that's relatively easy to account for which I go into great detail to explain.
- mpweiher 5y agoWhich is why the only sensible option is a proper numeric tower. Then the common cases are fast and the edge cases slightly slower, but everything works the same.
- cjbgkagh 5y agoI mostly use signed... but one of my primary activities is to use uint8, uint16, and uint32 for indexes and indexes into indexes etc. The workflow was designed around the various uint size limitations so that they are not exceeded. Uint32 is the largest chunk size that I use. The fact that it is twice as big as an Int32 is handy. It allows me to pass bigger chunks to the GPU. Plus I'm already working with uint8 and uint16 so it's consistent. I've not needed Uint64 or Int64 but it would vastly increase memory size for no benefit for my use case. Memory is cheap but I'm bottlenecked by memory bandwidth. I've looked into using variable ints but I haven't needed them yet. For things that I know I'm going to scan over having compressed variable ints of a diffed sorted bag would be great but I would need to write a ton of custom CPU and GPU code for it. You can index into variable ints with a post process provided a maximum number constraint and some padding on the end. This sort of code is written very carefully and mistakes give completely wrong answers so they are noticed right away.
- kazinator 5y agoThis is an misguided and dangerous article. Suppose that a, b and c are small values close to zero and so can be combined additively/subtractively in any combination without overflow. If they are signed, we can rely on algebra, like: a - b > c // this expression a - b - c > 0 // can become this expression a - c > b // or this This breaks for unsigned; you cannot just change the sign of c and move it to the other side of the inequality. Even when you're not actually doing this algebra in the code, it's useful to be able to do it outside of the code. Sometimes in the code too. For instance, suppose now that the values are not trivial. We have no assurance that a - b will not overflow, but we do have assurance from somewhere that a - c will not. The rewrite a - c > b is then helpful in avoiding overflow, and easily provable to be equivalent to the a - b > c expression that naturally comes from the problem specification.
- Diggsey 5y ago> Here’s a somewhat non-exhaustive list of all the undefined behavior of signed integer arithmetic in LLVM which applies to all languages which use LLVM: > These are certain to produce invalid results in languages like Go, Rust, and Odin. This is clearly untrue, since an operation (or indeed a type) at the language level need not translate to the same operation/type within LLVM. For example, none of these are "undefined behaviour" in Rust.
- int_19h 5y agoThe problem isn't that signed or unsigned is the accepted default. The problem is that bounded integers are the default, and worse yet, that their behavior at the edges is counter-intuitive from a common sense perspective. This was perfectly reasonable back when RAM was measured in kilobytes, and clock speed in megahertz. But these days, we write apps in HTML and JS, and package them with a browser to run. And, conversely, security is much more of a problem than it was decades ago - and integer overflow is a very common cause of security issues. So, why aren't unbounded integers becoming the norm? I'm not saying we should throw int32 etc out, but rather treat them as low-level optimization tools - much like we treat, say, raw pointers in C# or Rust. Surely the default should be safety over performance?
- ridiculous_fish 5y agoSeveral comments in this thread take the POV that "integer overflows never happen in practice" but of course they do! https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=integer+overflow https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=integer+ove... Of course uints overflow too, which just means arithmetic is hard, and it's often (not always) made harder when you have to consider negative values. Bounds checking, average, division, etc. INT_MIN is a horrible edge case which is easy to forget.
- jcelerier 5y agoI opened one at random and it's an uint overflow lol. https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-10879 https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-1087...
- ridiculous_fish 5y agoThe patch is completely bogus: https://github.com/teeworlds/teeworlds/commit/4d529dcd2d01022e979ebfa0b91167dee37cdb8e https://github.com/teeworlds/teeworlds/commit/4d529dcd2d0102... Here it tries to avoid overflow by assigning the result of 32 bit arithmetic to a 64 bit type. That's a common mistake.
- yath_ 5y ago> // But it also even has an explicit n * m form as well. > make([]Object, n, m); make([]T, m, n) does not allocate a slice of length n*m, but of length n and capacity m.
- cesarb 5y agoFor me, the main reason to prefer unsigned integers whenever possible is: less special cases. When a signed integer is used as an array index, the value can be in one of three ranges: the <0 range, the >=0 && <size range, and the >=size range. To validate the index, you need two comparisons. When an unsigned integer is used as an array index, there are only two ranges: the <size range, and the >=size range, and you need only a single comparison. And that's not the worst situation with signed integers. From a more general point of view, there are four "classes" of signed integer: positive (>0), zero, negative (<0), and INT_MIN. Everybody tends to forget about that last one, but it's "special" in that it can break things in unexpected ways. Negating it doesn't work (you'd expect negating any number less than zero to result in a number greater than zero, but for INT_MIN that doesn't happen). Dividing it can trap (see for instance https://kqueue.org/blog/2012/12/31/idiv-dos/ https://kqueue.org/blog/2012/12/31/idiv-dos/ which has a couple of examples) or worse. With unsigned integers, there are only two "classes", zero and non-zero, and it's common to not even need special treatment for zero, reducing the whole thing to a single "class" of values.
- phkahler 5y ago>> To validate the index, you need two comparisons. If your code doesn't have bugs, no validation of indexes is required.
- cesarb 5y ago> If your code doesn't have bugs, no validation of indexes is required. Your code doesn't have bugs because you validated your indexes. What you said makes some sense when the index comes from within the program itself, but not when it comes from outside the program. Consider for instance the case of reading a data structure from a file or the network, where one field is an index or an offset into another part of the structure; you must validate that this index or offset is not outside the bounds, no matter how perfect your code is.
- kingcharles 5y agoThe number of programs ever written without bugs can be counted in a uint8.
- davidfstr 5y agoFor languages that don't give you a choice of signed vs. unsigned - giving you signed and sometimes arbitrary-precision integers - this debate is irrelevant. I'll put it in my same mental bucket of "things that I no longer worry about", along with buffer overflows, wild pointers, etc that are eliminated by memory-safe languages.
- lisper 5y ago> It turns out that computing differences safely is actually quite hard for signed integers because of underflow, even in languages which support wrapping behavior for them, e.g INT_MAX - INT_MIN is still going to be incorrect even. There just isn’t a trivial way to do this safely And that right there is a compelling reason not to use C or C++. If the language is so broken that it doesn't even let me subtract signed integers safely without risking shooting myself in the foot it is worse than useless in today's world because it gives me the illusion of programming in a high-level language when in fact I am not. When I want to subtract x from y, I want to be able to write y-x and have the language worry about the details. That is the whole point of having a high level language, to abstract away the low-level details and let you write high-level abstractions without having to worry about introducing bugs that could imperil your entire enterprise. C and C++ don't do that.
- ncmncm 5y agoThis is the argument not to use computers at all. It is not persuasive. There is never a reason to use C. But C++ is a language for engineers. If you don't have the patience to do engineering, then you should not. If you have a need for engineering anyway, hire one.
- lisper 5y agoPart of engineering is choosing the right tools, and that means avoiding tools that have booby traps built in to their design unless there is a very compelling reason to accept that risk. C was a good tool when computers were much more resource-constrained than they are now and security was much less of a concern, but those days are long gone.
- ncmncm 5y agoPart of engineering is understanding your tools, and not imagining they are other than they are. There is no risk when there is no delusion. A professional will always choose the sharpest tool, and respect it. There are no booby traps, only booby programmers.
- beeforpork 5y agoI agree that signed is generally inferior and less often what you really need. For me, in C and C++, the main arguments for 'unsigned by default' are: (1) integer overflow/underflow is undefined behaviour. You don't want that, it's evil. Unsigned does not have that problem (often it is still a bug if you over- or underflow -- but at least you get sane code from the compiler). (2) size_t is unsigned and is returned by sizeof() and is the argument to memcpy(), strcpy(), etc., and with -Wconversion, you do not want to handle all the warnings when mixing this with signed loop counters or size variables. Unfortunately, one problem with using unsigned by default in C is that ptr1-ptr2 yields ptrdiff_t, which is signed. Which is bad, in my opinion, because I usually want to find an array size or index when I subtract two pointers, so I want size_t, and in these cases, I always know which pointer is larger. Oh well, it's C.
- InfiniteRand 5y agoOne thing with array indices is that using signed means that you need to always check for negative in addition to checking for too large. Unsigned indices means you can just check against too large. I think a lot of the scenarios where signed is safer are also situations where the application logic would be wrong, so I am a bit skeptical of that argument. But Ultimately the biggest factor to consider is what your team or prospective team members in your industry are used to, different industries tend to have people who never expect unsigned values vs those who always assume unsigned will be used.
- ulnarkressty 5y agoI've seen plenty of bugs due to misuse of unsigned types, mostly coming from beginners that are trying to fix type conversion during comparison compiler warnings. Then they go on and do some arithmetic with the loop index, which results in an underflow or two. We now have hard rules against unsigned usage if it is part of an arithmetic operation. Where things get a bit more tricky is when working with data that has some native unsigned type - e.g. when reading an image from file, it will mostly consist of unsigned chars. There you also need conversion rules and everyone aligned on algorithms, APIs etc. Mostly though it's a matter of maintainability - it's easier to wrap your head around signed integers (no pun intended), even for beginners.
- jeffreyrogers 5y agoI sometimes use signed ints to indicate an error condition. Then you know if the result is < 0 some error occurred, otherwise you can continue with normal processing.
- captainmuon 5y agoI wonder, is there any language that automatically promotes ints to more bits to ensure there is no overflow? The sum of two eight-bit ints is a nine-bit int (probably occupying 16 bits in memory, but that is an implementation detail): uint8 a = 230; uint8 b = 250; auto c = a + b; // typeof(c) == uint9 Maybe it would even be able to detect "c / 2" fits in an uint8. I guess this could lead to an explosion of bits required, but only if you chain multiple operations and use type inference. If you explicitly assign to a fixed-width integer, it would truncate. I know Python used bignums under the hood, but is there any compiled and/or strictly typed language that does this? Because it seems modulo arithmethic and silent under/overflow is most of the time not what you want.
- ncmncm 5y agoThat is generally not possible in a strongly-typed language unless you just use a bignum type to begin with. Most numbers are small, and you aren't worried about overflow. With big numbers, std::int64_t is hard to overflow. If you have numbers from an untrusted source, you can and should range-check them immediately on input.
- captainmuon 5y agoWhy not? Ada, Pascal, Nim and others have ranged integer types. Many modern languages use some kind of type inference. You could easily define that the type of an integer expression has to be large enough, for most expressions. It doesn't have to be general (I wouldn't be surprized if the general case is theoretically impossible). But you could fix the most obvious cases easily with this (for loops that can't go below 0 because of unsigned counters, calculating the average but the temporary overflows, ...). And if the compiler gives you a warning... "Inferred variable would require a bignum (int128)" then you could either silence it by specifying the type explicitly, or maybe you are missing a manual range-check? > If you have numbers from an untrusted source, you can and should range-check them immediately on input. You should, but you are going to forget in some places. The point of a stongly-typed language to me is that the compiler will make sure you do. It is the edge cases and the cases where you accidentially don't sanitize properly where you get evil bugs.
- BooneJS 5y agoLow-level programming, dealing with hardware registers, is so often unsigned that I use unsigned everywhere I don't need negative numbers. Youtube going 64-bit was inevitable, but overflowing 2^31 should not have been one of them. https://arstechnica.com/information-technology/2014/12/gangnam-style-overflows-int_max-forces-youtube-to-go-64-bit/ https://arstechnica.com/information-technology/2014/12/gangn...
- slaymaker1907 5y agoI prefer unsigned in Rust but signed for C/C++. This is mostly because I'm always afraid that the number will be silently converted to a signed type at some point. Rust is much more explicit about when these conversions happen so it worries me less.
- PaulDavisThe1st 5y agoI haven't seen anyone mention the main reason I end up using signed: to allow for an "out-of-bounds" value to indicate "value not set". As long as the N-1 bit version of the integer is large enough, not having to use an additional variable to indicate "var not set" is really quite lovely. One could potentially replace the use of a negative sentinel value with a maximum sentinel value, and I've done this on occasion too (i.e. if (var == 2^N-1) var-is-not-set). But the cognitive distinction between negative == not set, positive == valid value is easier to deal with (for me, at least).
- ncmncm 5y agoThis the proper place for std::optional<T>.
- PaulDavisThe1st 5y agothat has quite the overhead for something that can be done using a single bit of the actual value. roughly half the programming i do is high-performance real-time constrained. not really appropriate in that context.
- ncmncm 5y agoThere is a proper place for everything, and others for everything else. You can make a zero-overhead analog of optional<int>, for such cases, for clarity and safety. (Unless you are also trying to present a C API for cross-language compatibility...) But it is tricky to determine the exact amount of handholding to provide for such a type, and extra work to remember exactly what it is. We all know how ints work.
- defen 5y agoWhat I find interesting is that the implementation of `midpoint` is incorrect (should be `U difference = (U)y - (U)x;`), which is not a good look when you want to argue that unsigned makes everything more correct.
- togaen 5y ago“In many ways signed integers are the null pointers of integers.” What a great article.
- TD-Linux 5y agoI am surprised to see what I consider to be the most important part of signed integers in C and C++ only barely mentioned: >use of signed integers is better as it’s the only way you can get trap behavior for integers, as using it on unsigned would trigger trap representations for valid code that relies on that behavior. For video and audio codec code, and really anything integer math heavy, being able to use UBSan to find overflows is a hugely beneficial tool, and something you can normally only do with signed integers due to the C spec (it's less of an issue in Rust as that language makes both signed and unsigned overflow illegal). >Trap representations are actually quite insufficient as they can only trigger at runtime when those paths are successfully executed with the correct trap-producing inputs. This coverage is impossible to expect in any non-trivial program even with exhaustive unit testing. This was true before fuzzers existed, but now that we have several very good fuzzer implementations (plus a few smart unit tests), the coverage is well within reach.
- mpweiher 5y agoTo me signed vs. unsigned by default seems like asking which leg to cut off by default, left or right? The correct default IMHO, is a proper numeric tower paired with a tagged pointer implementation for "small" integers (range in ~ ± 2^62 or so). As others have pointed out, this will essentially never overflow in practice, so memory traffic is the same as for 64 bit primitive integers. AFAICT, we are now good enough at optimising tagger pointer/small integer arithmetic that on modern machines, memory traffic should be the limiting factor. I was vascillating between different options (for Objective-S, http://object.st http://object.st) for a long time, because while I love C's "cheap and cheerful" use of int, but I also love Smalltalk's (and LISP etc.) "we do the right thing". What pushed me over the edge towards the numeric tower as default position was DJB's retrospective paper in Qmail security: https://cr.yp.to/qmail/qmailsec-20071101.pdf https://cr.yp.to/qmail/qmailsec-20071101.pdf So while "cheap and cheerful" works really well in regular situations, it does not work well at all when you're under attack, because attackers will go 100% for the edge cases, the ones that "never happen". So we really need to, as DJB put it, "simplify integer semantics". Having those overflows just cause a small slowdown seems like a reasonable tradeoff, we don't need attacks to execute at optimal efficiency. Given the advances we have in software and hardware, there simply is no reasonable case to be made for not having a proper numeric tower as default. When you need better performance or specialised semantics, the primitive types should be readily available. But not the default.