3

I'm getting -Wconversion warning in C.

conversion from 'int' to 'uint8_t' {aka 'unsigned char'} may change value [-Wconversion]

When performing the following operation:

uint8_t output_A = 0x00;
uint8_t output_B = 0x00;
uint8_t example = 0x83;

output_A |= (uint8_t)((example & 0x01) << 7); /* No warning */
output_B |= (uint8_t)((example & 0x01) << 6); /* Warning */

uint8_t output_C = 0x00;
output_C |= (uint8_t)((example & 0x01) << 22); /* No warning */

Why is there warning for case B but not for case A? I would expect either warning for both or neither.

Why is there no warning in case C? In that case, the value gets promoted to int, before we cast it to uint8_t and lose information.

Using gcc 10.3.1.

Lundin
  • 195,001
  • 40
  • 254
  • 396
wzs
  • 31
  • 2
  • 5
    Because the warning is no longer present in 10.4, I suspect a compiler bug. – KamilCuk May 16 '23 at 09:05
  • `-Wconversion` means "give me various warnings related to integer conversions, along with a lot of false positives". It was always a buggy option not to be trusted. – Lundin May 16 '23 at 09:36
  • Btw realize that these are equal to `output_A = output_A | (uint8_t)(...);` where both operands of `|` are implicitly promoted to `int`. So the casts solve nothing. And for that reason, compound assignment isn't really recommended in high integrity systems (MISRA C and similar) where implicit promotions are banned. – Lundin May 16 '23 at 11:34

0 Answers0