static_cast返回-1是为什么

huangapple go评论61阅读模式
英文:

Why static_cast<> is returning -1

问题

I am working on a bug in an Application where acquiring data is not able to complete. Just assume it's one of the actions by the user and internally we are computing and displaying some information. The issue is occurring after migrating Visual Studio from 2010 to 2019.

I figured out the reason is because the below statement is returning '-1', but I'm not able to understand why it's returning '-1' instead of '-2570':

int acqElevStartECount = -2302;
int accElevECounts = 68;
int cvSettleCount = 200;

int startElevECount = static_cast((double)acqElevStartECount - accElevECounts - cvSettleCount);

If I remove '(double)' from the statement, it works fine.

FYI, it's legacy code which was working fine in Visual Studio 2010. Moreover, I don't know why they are converting 'int' data type to 'double' then to 'unsigned int'.

I wanted to know the reason why it is returning '-1'.

英文:

I am working on a bug in an Application where acquiring data is not able to complete. Just assume it's one of the actions by the user and internally we are computing and displaying some information. The issue is occurring after migrating Visual Studio from 2010 to 2019.

I figured out the reason is because the below statement is returning -1, but I'm not able to understand why its returning -1 instead of -2570:

int acqElevStartECount = -2302;
int accElevECounts  = 68;
int cvSettleCount = 200;

int startElevECount = static_cast&lt;unsigned int&gt;((double)acqElevStartECount - accElevECounts - cvSettleCount);

If I remove (double) from the statement, it works fine.

FYI, it's legacy code which was working fine in Visual Studio 2010. Moreover, I don't know why they are converting int data type to double then to unsigned int.

I wanted to know the reason why it is returning -1.

答案1

得分: 3

浮点数的值为-2570,超出了unsigned int可表示值的范围,将这样的浮点数转换为整数会导致未定义的行为。不要这样做。

英文:

> I wanted to know the reason why it is returning -1.

The floating point number has the value of -2570 which is outside the range of representable values of unsigned int. Converting such floating point number to integer results in undefined behaviour. Don't do that.

huangapple
  • 本文由 发表于 2023年4月7日 04:13:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定