Compiling the following code
// foo.c
typedef unsigned char uint8_t;
int main() {
uint8_t a = 1;
uint8_t b = 10;
uint8_t c = 12;
uint8_t k = a + b + c;
}
using GCC 11.2 (also other GCC versions) with the following full-command:
gcc -Wconversion foo.c
Results in the following warning:
Output of x86-64 gcc 11.2 (Compiler #3)
<source>: In function 'main':
<source>:11:17: warning: conversion from 'int' to 'uint8_t' {aka 'unsigned char'} may change value [-Wconversion]
11 | uint8_t k = a + b + c;
| ^
Compiler returned: 0
This does not happen when adding two unsigned chars, i.e. a + b, for example.
It happens when using any combination of arithmetic operations between more than three unsigned chars.
And it does not happen with clang version 12.0.1.
Why does a + b + c, for example, result in an int that must be cast to uint8_t before assigning to k to supress the warning?