Search code examples
cimplicit-conversioninteger-promotion

Size of unsigned char is 8 bits but why can I shift it (left or right) by or upto 31 bits?


So here is my code

#include <stdio.h>                  
int main(void) {
    unsigned char ch = 244;      
    ch = ch << 31;                   
    return 0;
}

I can shift ch upto 31 bits that's means ch is of 32 bits but how ? sizeof(ch) is also 1 byte only.


Solution

  • [...] that means ch is of 32 bits [...] ?

    It isn't. The result of the shift, which is of type int, is truncated to 8 bits when assigned back to ch.

    You can verify this by examining the value of ch.

    gcc spots this if -Wconversion is turned on:

    $ gcc -Wconversion test.c
    test.c:4:13: warning: implicit conversion loses integer precision: 'int' to 'unsigned char' [-Wconversion]
        ch = ch << 31;
           ~ ~~~^~~~~
    1 warning generated.