C: What happens (in detail) in x=~x if x is of type char?

  • A+

If we have the following code:

char x = -1; x =~x; 

On an x86 platform with MS VS compiler (which partly supports C99) - what happens in detail when it is running?

To my knowledge, the following happens (please correct me if I am wrong):

  • x is assigned the value -1, which is represented by the bit pattern 0xff since a char is represented by one byte.
  • The ~ operator promotes x to an int, that is, it internally works with the bit pattern 0xffffffff.
  • The ~ operator's result is 0x00000000 (of type int).
  • To perform the assignment, the integer promotions apply (principally). Since in our case the operand on the right hand side is an int, no conversion occurs. The operand on the left hand side is converted to int. The assignment's result is 0x00000000.
  • As a side effect, the left hand side of the assignment is assigned the value 0x00000000. Since x is of type char, there is another implicit conversion, which converts 0x00000000 to 0x00.

There are so many things that actually happen - I find it somehow confusing. In particular: Is my understanding of the last implicit conversion (of int to char) correct? What would happen if the assignment's result could not be stored in a char?


Indeed ~x is an int type.

The conversion back to char is well-defined if char is unsigned. It's also well-defined, of course, if the value is in the range supported by char.

If char is signed, then the conversion of ~x to char is implementation-defined, with the possibility that an implementation defined signal is raised.

In your case, you have a platform with a 2's complement int and a 2's complement char, and so ~x is observed as 0.

Note that MSVC doesn't fully support any C standard, and neither does it claim to.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: