Search code examples
cbitwise-operatorsnegationinteger-promotion

Negation operator on unsigned char


#include <stdio.h>
int main() {
    unsigned char a = 5;
    printf("%d\n",~a);
    printf("%d\n",a=~a);
    return 0;
}

According to the accepted answer here Negation inside printf , in the first printf, a should get promoted to an int and the output should be a large negative number. But the output of the first printf is -6. Can you please explain why the output is -6 and why the char is not promoted to int in this case?


Solution

  • Can you please explain why the output is -6 and why the char is not promoted to int in this case?

    Not really, because it is being promoted to an int - and, as an int, inverting all the bits will (assuming two's-complement notation and no overflow) convert a positive n value into the negative value, -(n+1).

    This modification to your code may demonstrate what's happening:

    #include <stdio.h>
    int main()
    {
        int a = 5;
        printf("%d\n", ~a); // Prints -6
        printf("%d\n", a = (unsigned char)~a); // Prints 250 - lower 8 bits of the int
        return 0;
    }