On 28/11/2018 13:56, Emil Dotchevski wrote:
As should hopefully be obvious, implicit narrowing conversions are never a good idea.
short f();
short x = f(); short y = x+1; //Implicit conversion from int to short.
Do you think the compiler should warn in this case? Is the version below better? Safer?
short y = static_cast<short>(x+1);
No, that's a language defect. In that context "1" should be of type short (because as a literal, it can be) and then it should apply "short operator+(short, short)", and then there would be no problem (assuming it doesn't overflow). (Or as a general rule, the literal "1" should actually be type int8_t, because that's the smallest signed type which includes its value, and can always be safely implicitly extended to a larger type based on usage.) I am aware that the language does not work like this currently. This is one of the things that make it so easy to produce incorrect code.