Conversion warning when adding two uint8_t

I don't really understand where the int comes from.

int comes from the C language standard. All operands of arithmetic operators are promoted before performing their operation. In this case uint8_t is promoted to an int, so you need a cast to avoid the warning:

res = (uint8_t)(a + b);

Here is how the standard defines integer promotions:

6.3.1.1 If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.

Since int can hold all possible values of uint8_t, a and b are promoted to int for the addition operation.


Just to add to the existing answer about integer promotions, it might also be worth explaining what -Wconversion is warning you about.

Since a and b are both uint8_ts, the result of a + b might not fit in another uint8_t. By assigning the result back into a uint8_t, you force the compiler to perform a conversion which might change the value. Hence, the res variable might not actually represent the actual value of a + b.

For example, if a and b were both 0xff, then:

  • a + b is 0x1fe and has type int
  • (uint8_t)(a + b) is 0xfe