Why does stdlib.h's abs() family of functions return a signed value?

被刻印的时光 ゝ 提交于 2019-12-04 02:29:33

The real answer to this question lies in the type promotion rules.

If I apply an arithmetic operator to an unsigned int and an int, then the int argument is promoted to unsigned, and the result is also unsigned.

If the abs() function returned unsigned, then it would cause this kind of type promotion of other values when it was used in an expression, which would cause unexpected results. For example, this code:

if (abs(-1) * -1 < 0)
    printf("< 0\n");
else
    printf(">= 0\n");

Would print ">= 0", which many wouldn't like. The tradeoff, of not being able to use the single value INT_MIN, presumably seemed OK.

Why would it ever return a value using the unsigned space?

Let's consider 8 bit signed and unsigned numbers. If you have -128, the result is undefined... I guess stdlib doesn't want to slow things down that much. If you think you might have a number in that range, then you need to use something else.

If you think you might have a value greater than 127 in your signed char, then you are mistaken.

Ergo, it is unnecessary for the value to be able to hold a value greater than 127, and keeping it signed loses nothing. If you want to cast it to unsigned, go ahead. Since it just used to be a signed integer, the odds are good that you will be doing signed math again. Personally, I think I'd prefer that the type stay signed, since it is pretty rare that I actually want to be dealing with unsigned and I'm not doing bit operations.

But maybe someone else can dig up some notes from the standards committee.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!