Why doesn't C have unsigned floats?

后端 未结 12 1658
名媛妹妹
名媛妹妹 2020-11-28 01:47

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

12条回答
  •  被撕碎了的回忆
    2020-11-28 02:29

    Good Question.

    If, as you say, it is only for compile-time warnings and no change in their behavior otherwise then the underlying hardware is not affected and as such it would only be a C++/Compiler change.

    I have wonedered the same previously, but the thing is: It would not help much. At best the compiler can find static assignments.

    unsigned float uf { 0 };
    uf = -1f;
    

    Or minimalistically longer

    unsigned float uf { 0 };
    float f { 2 };
    uf -= f;
    

    But that's about it. With unsigned integer types you also get a defined wraparound, namely it behaves like modular arithmetic.

    unsigned char uc { 0 };
    uc -= 1;
    

    after this 'uc' holds the value of 255.

    Now, what would a compiler do with the same scenario given an unsigned float-type? If the values are not know at compile time it would need to generate code that first executes the calculations and then does a sign-check. But what when the result of such a computation would be say "-5.5" - which value should be stored in a float declared unsigned? One could try modular arithmetic like for integral types, but that comes with its own problems: The largest value is unarguably infinity .... that does not work, you can not have "infinity - 1". Going for the largest distinct value it can hold also will not really work as there you run into it precission. "NaN" would be a candidate. You lose any and all information what the number originally contained - not really helpful as you now would need to check for that specifically so you might as well check if the number is positive your self.

    Lastly this would not be a problem with fixed point numbers as there modulo is well defined.

提交回复
热议问题