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?
If the value falls within the range of a
short
then the value is guaranteed to be correct, which in your case is true, soy == 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.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":Since
short
is guaranteed to be able to hold the value200
(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.