What does the C ++ standard say about how static_cast handles integer reduction?

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

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

Is y guaranteed 200, or does the standard leave this solution to the decision? How well do different compilers fit the standard?

+6
c ++ casting
source share
2 answers

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

If the destination type is signed, the value does not change if it can be represented in the destination type (and bit width); otherwise, the value is determined by the implementation.

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

Various compilers adhere to this behavior quite well - this has been the case since the days before ANSI C and so much code depends on the behavior that compiler manufacturers seem reluctant to even warn about truncation.

+9
source share

If the value is in the range from short , then the correctness of the value is guaranteed, which in your case is true, therefore y == 200 .

If it goes outside (e.g. static_cast<short>(1000000000) ), then the behavior is undefined. Most compilers simply truncate binary digits to the desired size.

-2
source share

All Articles