一元减号和浮充转换的组合 [英] combination of unary minus and float conversion

查看:145
本文介绍了一元减号和浮充转换的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的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.

这篇关于一元减号和浮充转换的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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