开发者

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

开发者 https://www.devze.com 2022-12-19 16:45 出处:网络
I would like to know the 开发者_开发问答rules specified by the C++ language standard for situations like:

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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号