Why doesn't C have unsigned floats?

Nils Pipenbrinck picture Nils Pipenbrinck · Feb 4, 2009 · Viewed 85.7k times · Source

I know, the question seems to be strange. Programmers sometimes think too much. Please read on...

In C I use signed and unsigned integers a lot. I like the fact that the compiler warns me if I do things like assigning a signed integer to an unsigned variable. I get warnings if I compare signed with unsigned integers and much much more.

I like these warnings. They help me to keep my code correct.

Why don't we have the same luxury for floats? A square-root will definitely never return a negative number. There are other places as well where a negative float value has no meaning. Perfect candidate for an unsigned float.

Btw - I'm not really keen about the single extra bit of precision that I could get by removing the sign bit from the floats. I'm super happy with floats as they are right now. I'd just like to mark a float as unsigned sometimes and get the same kind of warnings that I get with integers.

I'm not aware of any programming language that supports unsigned floating-point numbers.

Any idea why they don't exist?


EDIT:

I know that the x87 FPU has no instructions to deal with unsigned floats. Lets just use the signed float instructions. Misuse (e.g. going below zero) could be considered undefined behaviour in the same way as overflow of signed integers is undefined.

Answer

Brian R. Bondy picture Brian R. Bondy · Feb 4, 2009

Why C++ doesn't have support for unsigned floats is because there is no equivalent machine code operations for the CPU to execute. So it would be very inefficient to support it.

If C++ did support it, then you would be sometimes using an unsigned float and not realizing that your performance has just been killed. If C++ supported it then every floating point operation would need to be checked to see if it is signed or not. And for programs that do millions of floating point operations, this is not acceptable.

So the question would be why don't hardware implementers support it. And I think the answer to that is that there was no unsigned float standard defined originally. Since languages like to be backwards compatible, even if it were added languages couldn't make use of it. To see the floating point spec you should look at the IEEE standard 754 Floating-Point.

You can get around not having an unsigned floating point type though by creating a unsigned float class that encapsulates a float or double and throws warnings if you try to pass in a negative number. This is less efficient, but probably if you aren't using them intensely you won't care about that slight performance loss.

I definitely see the usefulness of having an unsigned float. But C/C++ tends to chose efficiency that works best for everyone over safety.