Does uint16_t gets promoted to int?
If int
is 32 bits, sure. If not, then it isn't promoted.
I was expecting that b would get promoted to int
It is, on a 32 bit system.
But the compiler did not raise any warning.
It's not really the compilers job to keep track of that. If you get a warning, it's just a bonus. But also please note that in your example the conversion is done in two internal steps: first the integer promotions is performed on the uint16_t
making it int
. But then immediately afterwards, the usual arithmetic conversions convert that int
to a uint32_t
. So essentially as far as the programmer is concerned, the uint16_t
is converted to uint32_t
and that conversion is always safe.
Generally, operations mixing unsigned operands of different sizes are safe.
if (a > (uint32_t)(b * 10))
b
gets promoted to int
and 10
is already int
. There's no way for the multiplication to overflow since it can't get larger than 655350. You can cast to uint32_t
afterwards if you like, but it doesn't rally achieve anything except being explicit.
More rugged code would have done the cast before the multiplication or perhaps used 10u
instead. But in this specific case it really don't matter.
b * 10
is promoted to signedint
, because10
is signedint
. – Malayalam10u
to keep it unsigned. – Zoharab
toint
can't possibly result in a negative value, and suppress the spurious warning. – Lightfootedint
in first case? Also is it safe to typecastuint16_t
touint32_t
? – Pumping>
maybe). – Interfluentb
. If anint
can represent all values ofb
's type, then it is promoted to anint
. But on a machine with 16-bit integers, that would not be the case. So in the first case, the multiplication would be applied to two signed integers. But in the latter, it would be an unsigned integer and a signed integer, so it would be unsigned. At least, that's how I read the standard. – Bontebok*
operator says that integer promotions are performed at the operands. And then since both operands happen to have typeint
, no further conversions are necessary. In case it had saidb * (unsigned short)10
,b
would still have been promoted toint
. – Interfluentuint16_t
corresponds tounsigned int
so it won't get converted, but the10
would get converted touint16_t
. – Interfluentb
would be left unchanged and the10
would become unsigned. So in that case the result would be unsigned. I mentioned that in my earlier comment. – Bontebokint
regardless of previous signedness. And from there, if two operands have the same conversion rank, it picks unsigned over signed. – Interfluent