Type promotion in C

Jeff posted on  (updated on )

Check following code snippet written in C:

    uint8_t h = 0xff;

    uint8_t a = h << 8;
    uint16_t b = h << 8;
    uint16_t c = (h << 8) + h;
    printf("a: %x\nb: %x\nc: %x\n", a, b, c);

Above program prints

a: 0
b: ff00
c: ffff

I used to think I need to write like this to avoid losing information (like variable a)
(uint16_t)h << 8

But apparently not, the type promotion would perform (by whom? compiler at compile time? or run time?), and all variables are casted to int if it can hold the original value, in our example, int is enough to hold 8 or 16 bit information.

https://stackoverflow.com/questions/7954717/type-promotion-in-c

And of course when the intermediate calculation is done, the result is casted back to the designated variable, like uint8_t for variable a.