1

Why am I getting :

(373)implicit signed to unsigned conversion

by doing:

fan_on_hh = hh + fan_hh_increment

All fan_on_hh, hh and fan_hh_increment are unsigned char.

enter image description here

This post suggests to do this:

fan_on_hh = (unsigned char) hh + fan_hh_increment

But I keep getting the same warning by doing that.

Is there a way to stop these warnings?

Mike
  • 4,041
  • 6
  • 20
  • 37
Andras
  • 401
  • 2
  • 15
  • 1
    You get implicit conversion to `int` in the addition. – Ted Lyngmo Feb 12 '23 at 19:09
  • 2
    Doing `+` promotes the inputs, and the result, back up to `int`. You have to cast the result of the `+` (note `+` has lower precedence than a cast). See https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules for more. – Nate Eldredge Feb 12 '23 at 19:09
  • Use `fan_on_hh = (unsigned char)(hh + fan_hh_increment)` or maybe `fan_on_hh = (hh + fan_hh_increment)&UCHAR_MAX`. IMO, this warning should not occur as conversion `int` to `unsigned char` is well defined. - IOWs, a weak analysis tool. – chux - Reinstate Monica Feb 12 '23 at 19:46

2 Answers2

1

As others have stated, you can cast the result of the addition, which is probably the right way to go about it. But if that message is particularly annoying, the manual suggests (section 4.5.3.1 Disabling Messages) adding some flags to the command line to disable it:

-Xparser -Wno-sign-conversion
xorFF
  • 21
  • 4
0

Integer types smaller than int (e.g. unsigned char) are promoted to int when an operation is performed on them. If all values of the original type can be represented as an int, the value of the smaller type is converted to an int.
So in your example hh and fan_hh_increment are promoted to int before the addition.
When you want to stop the warning, you had to cast the result to unsigned char:

fan_on_hh = (unsigned char) (hh + fan_hh_increment); 
Mike
  • 4,041
  • 6
  • 20
  • 37