Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

casting

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?

like image 223
ReWrite Avatar asked Feb 11 '10 02:02

ReWrite


People also ask

What is the purpose of the static_cast operator?

The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.

What happens when you perform a static_cast?

Static Cast: This is the simplest type of cast which can be used. It is a compile time cast.It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones).

Is static_cast backwards compatible with C?

Since C++ is 99% backwards-compatible with C, most C source code can be compiled as C++ source code and will work, and in that scenario, static_cast could be part of the code and would compile.

Why do we use static_cast in C++?

The static_cast is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coercion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. This can cast related type classes.


1 Answers

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.

like image 85
Michael Burr Avatar answered Oct 21 '22 17:10

Michael Burr