一元减号和浮充转换的组合

编程入门 行业动态 更新时间:2024-10-13 14:25:46
本文介绍了一元减号和浮充转换的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑下面的C语句:

unsigned long x = 1; float a = -x; double b = -x;

我希望一元减术语,以产生一个unsigned long值等于ULONG_MAX和A和B分别设为ULONG_MAX的单,双precision重新presentations。

I would expect the unary minus term to yield an unsigned long value equal to ULONG_MAX and a and b to be set to single and double precision representations of ULONG_MAX, respectively.

这是结果我与32位Linux,并与64位Linux的英特尔和PGI编译器GCC 4.4.7获得。与海湾合作委员会的64位Linux(测试版本4.4.7,4.7.2和4.8.0,都与-O0和-O2),然而,双变量B的预期值,但浮动等于-1来代替。

This is the result I obtain with gcc 4.4.7 on 32-bit Linux and with the Intel and PGI compilers on 64-bit Linux. With gcc (tested versions 4.4.7, 4.7.2 and 4.8.0, both with -O0 and -O2) on 64-bit Linux, however, the double variable b has the expected value, but float a becomes equal to -1 instead.

相反,下面的语句将A和B都设置为浮动ULONG_MAX点重新presentations所有的编译器和系统我测试:

By contrast, the following statements will set both a and b to floating point representations of ULONG_MAX on all compilers and systems I tested:

unsigned long x = 1; unsigned long y = -x; float a = y; double b = y;

如果我使用unsigned int类型,而不是无符号长的,我得到的所有系统上的预期的结果了。

If I use unsigned int instead of unsigned long, I get the expected result on all systems, too.

这是某种不确定的行为或编译器错误?

Is this some kind of undefined behaviour or a compiler error?

推荐答案

这是由于错误的GCC - 否定之前的类型转换发生

This is due to a bug in GCC -- the type conversion happens before the negation.

这个问题似乎已经存在了一段时间。 错误55771 - 否定与类型转换错误交换

The issue seems to be have been around for a while. Bug 55771 - Negation and type conversion incorrectly exchanged

在第二个例子中,否定类型转换之前发生。因此,你看到预期的效果。

In your second example, the negation happens before the type conversion. As such, you see expected results.

更多推荐

一元减号和浮充转换的组合

本文发布于:2023-11-29 12:14:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646368.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:减号   组合

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!