What does the C++ language standard say about how static_cast handles reducing the size of an integer?

喜你入骨 提交于 2019-12-19 07:53:16

问题


I would like to know the rules specified by the C++ language standard for situations like:

long x = 200;
short y = static_cast<short>(x);

Is y guaranteed to be 200, or does the standard leave this up to the implementation to decide? How well do various compilers adhere to the standard?


回答1:


In this case the static_cast<> is an 'explicit type conversion. the standard has this to say about integral conversions in 4.7/3 "Integral conversions":

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

Since short is guaranteed to be able to hold the value 200 (short must be at least 16 bits), then for your specific example the answer is yes.

Various compilers adhere to this behavior quite well - it's been that way since the pre-ANSI days of C, and so much code depends on the behavior that compiler vendors seem reluctant to even issue warnings about the possibility of truncation.




回答2:


If the value falls within the range of a short then the value is guaranteed to be correct, which in your case is true, so y == 200.

If it falls outside (e.g. static_cast<short>(1000000000)) then the behaviour is undefined. Most compilers will just truncate the binary digits down to the correct size.



来源:https://stackoverflow.com/questions/2241897/what-does-the-c-language-standard-say-about-how-static-cast-handles-reducing-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!