Does C++ allow any integer literal to be implicitly converted to a short int?
c++, compiler-warnings, literals, type-conversion, visual-c++
Solution
The standard allows the implicit conversion between any two integer types, regardless of their values.
The compiler warnings are unrelated to the code being legal; the compiler just warns you when your code probably does not do what you wanted it to.
In your specific case, `n1` would be 8 and `n2` would have an implementation defined value. Both assignments are legal C++, but the latter is probably not what you intended.
Relevant standardese:
A prvalue of an integer type can be converted to a prvalue of another integer type. A prvalue of an unscoped enumeration type can be converted to a prvalue of an integer type. If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ] 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.
4.7/1-3 in N4141
Problem
``` int main() { short n1 = 8ll; // no warning // warning C4305: 'initializing': truncation from '__int64' to 'short' // warning C4309: 'initializing': truncation of constant value short n2 = 88888ll; } ``` My compiler is Visual Studio 2017. According to cppref: The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used. The integer literal with suffix `ll` should be of `long long int`; so `short n1 = 8ll` should trigger a warning like `short n2 = 88888ll` does. Does C++ allow any integer literal to be implicitly converted to a `short int` if it is small enough?