加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么GCC会破坏用短参数调用abs函数的代码?

发布时间:2020-12-16 03:46:26 所属栏目:百科 来源:网络整理
导读:#include cmath#include cstdlibint main(){ short int k = 11; switch(std::abs(k)) { case 44: return 5; break; }} 上面的代码在GCC 4.4.7和7.1及更高版本中工作正常. 它在GCC 4.5.4及更高版本中出错: source: In function 'int main()':source:7:23: er
#include <cmath>
#include <cstdlib>

int main()
{
    short int k = 11;
    switch(std::abs(k)) {
        case 44:
            return 5;
            break;
    }
}

上面的代码在GCC 4.4.7和7.1及更高版本中工作正常.
它在GCC 4.5.4及更高版本中出错:

<source>: In function 'int main()':
<source>:7:23: error: switch quantity not an integer

所以我的问题是为什么GCC引入了这个突破性的变化?

或者,实施者是否意识到这是一个重大改变?如果是这样,为什么他们如何测试他们不破坏现有代码?

这个问题也可以针对Clang,因为它与abs函数有类似的问题.

解决方法

GCC(和clang)库(分别为glibc和libc)破坏了向后兼容性以符合C标准.

麻烦是由这个条款造成的:

Moreover,there shall be additional overloads suffcient to ensure:

  1. If any arithmetic argument corresponding to a double parameter has type long double,then all arithmetic arguments corresponding to
    double parameters are effectively cast to long double.

  2. Otherwise,if any arithmetic argument corresponding to a double parameter has type double or an integer type,then all arithmetic
    arguments corresponding to double parameters are effectively cast to
    double.

  3. Otherwise,all arithmetic arguments corresponding to double parameters have type float.

short int是“整数类型”,因此bullet#2启动并导致生成一个调用double abs(double)的包装器,这个包装器比int abs(int)更好.

值得注意的是,标准的最新草案在此规则中添加了明确的例外:

For each set of overloaded functions within,with the exception of abs,there shall be additional overloads suffcient to ensure:

此异常实际上源自handling of unsigned types,但也解决了您的问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读