为什么stdlib.h中的ABS()系列函数返回一个符号值? [英] Why does stdlib.h's abs() family of functions return a signed value?

查看:146
本文介绍了为什么stdlib.h中的ABS()系列函数返回一个符号值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此的消极的暗示在手册页指出:

The negative implication of this is noted in the man page:


         尝试最负整数是取绝对值
  不
         定义。

NOTES Trying to take the absolute value of the most negative integer is not defined.

什么是这背后的道理,什么是为想避免不确定的行为谁的人最好的追索权?我必须诉诸这样的:

What's the reasoning behind this and what's the best recourse for a person who would like to avoid undefined behavior? Do I have to resort to something like:

unsigned uabs(signed val) {
    return val > 0
        ? val
        : (val == 1U << ((sizeof(val) * 8) - 1))
            ? -1U
            : -val;
}

(故意哈克强调的不满STDLIB; - )

(Intentionally hacky to emphasize displeasure with stdlib ;-)

假设你有一个4位有符号值(为便于理解)。无符号最大值是15,签署(正)最多为7个,签约(负)分-8,所以ABS(-8)将不适合成为一个符号值。当然,你可以把它重新present为-8,但随后除法和乘法,结果如预期不起作用。

Say you had a 4-bit signed value (for ease of understanding). unsigned max is 15, signed (positive) max is 7, signed (negative) min is -8, so abs(-8) won't fit into a signed value. Sure, you can represent it as -8, but then division and multiplication with the result don't work as expected.

推荐答案

真正的答案在于类型提升规则。

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

如果我申请算术运算符将 unsigned int类型 INT ,那么 INT 参数提升为无符号,结果也是无符号

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.

如果在 ABS()函数返回无符号,那么它会导致这种类型的推广等值的当它在一个前pression,这会导致意想不到的结果被使用。例如,该code:

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");

将打印> = 0,这很多人会不喜欢。权衡,不能够使用单值 INT_MIN 中,presumably似乎确定。

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

这篇关于为什么stdlib.h中的ABS()系列函数返回一个符号值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆