英文:
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
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<unsigned int>((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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论