Re: [boost] Algebraic abstractions related to (big) integers in C++

On 3/29/11 21:57 Thomas Klimpel wrote:
So there exists an int value for which the assertion "assert(std::abs(i) >= 0);" fails. But when you convert the result of std::abs to unsigned, you get at least the correct >value.
Shouldn't that be another theoretical win for the 2's complement representation? I would say that the problem here is really that std::abs(int) returns another value of type int even though its range is logically unsigned. If you'd used printf("%u", std::abs(i)) instead of std::cout you would have seen the expected result. There's a certainly a tradeoff here--- if std::abs() is defined to return an unsigned value then it requires an explicit cast to be safely mixed with signed integers in many expressions, but if it's defined to return a signed value then its result requires a cast before being printed or converted to a float (at least when the argument to abs() is unconstrained.) I think the latter was the more pragmatic choice (note also that it can always be safely mixed into /unsigned/ integer expressions.) On 3/29/2011 14:06 Lucanus Simonson wrote:
I've heard this rationale before. He is serious. Promoting 32 bit unsigned to 32 bit signed, for example, could overflow, so is clearly not safe. Promoting signed to >unsigned is just as bad, of course, but it won't overflow.
Again, pragmatic. There's a *lot* of code that uses signed variables in contexts where an unsigned would do, and overflow normally occurs much more frequently than the corner cases where 'abs(x) == x' is not an identity for 'x >= 0'. From a certain software engineering perspective overflow can be more easily detectable and is thus preferable to logic bugs, but I'd imagine that unintended integer promotions are negligible in comparison to other sources of software defects. Like many things in C/C++, the tools to avoid a problem (explicit casting) are there, but it's up to you to recognize when and how to use them.
I'd like a compiler warning for all auto promotion of signed to unsigned so that I can inspect the line and see if I think it is safe. If it happens when you didn't realize it
-Wsign-conversion and -Wsign-compare will catch most abuse in GCC, but they generate considerable amounts of noise on many codebases (and nothing but pain for something like the Linux kernel.)
participants (1)
-
Brent Spillner