4

I am confused by the following code:

char c = 0x66;
printf("~c = %x\n", ~c); //0xffffff99
printf("size of c: %d\n", sizeof(c)); //1 byte
printf("Size of ~c: %d\n", sizeof(~c)); //4 bytes

A char only has 1 byte but the result will be 4 bytes using the ~ operator. Why is the result of ~c 0xffffff99 rather than 0x99?

Are there some mistakes I have made?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
iwanderer
  • 91
  • 5

1 Answers1

6

What you are seeing is the result of integer promotion. Almost all operations on integral types smaller than the standard int type (such as char and short) are performed on data promoted to the int type, and the results of those operations are also of the promoted type. This promotion rule includes the unary ~ operator.

From this C11 Draft Standard (bolding mine):

6.5.3.3 Unary arithmetic operators

...
4 The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.

On your system, the size of the (promoted) int type is 4 bytes.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83