Search code examples
ccastingintwarningsinteger-promotion

Conversion warning when adding two uint8_t


I have the following C code:

typedef unsigned char uint8_t;

void main(void) {
    uint8_t a = 1, b = 2, res;
    res = a + b;
}   

When I compile this code using gcc -Wconversion, I get the following warning:

test.c: In function 'main':
test.c:5:10: warning: conversion to 'uint8_t' from 'int' may alter its value [-Wconversion]

Can someone please explain why this warning appears? All three variables are of type uint8_t, so I don't really understand where the int comes from.


Solution

  • 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.