Type conversions

All come from section 2.7 of the c programming language 2nd edition. BTW, this book is highly recommended for learning C, it's simple and illustrates the very important aspects of C.

When an operator has operands of different types, they are converted to a common type. The general rule is that convert a 'narrower' operand to a 'wider' one without losing information, the result is the 'wider' one. For example, for signed char + int, the char is promoted to int; for unsigned char + int, the unsigned char is promoted to int.

For signed and unsigned operator of same type, promote to unsigned. For example, for unsigned int + signed int, the signed int is promoted to unsigned int.

Conversions take place across assignments; the value of right side is converted to the type of left, which is the type of result. For example, int = unsigned char + signed char, both unsigned char and signed char in the right is converted to int before doing add. When left type is unsigned and right type is signed, the right type is first promoted to left type as signed, then converted to unsigned. For example,  unsigned int = unsigned char + signed char, the right signed char is first promoted to signed int, then converted to unsigned int.

A note to char type, the language does NOT specify whether a variable of char is signed or unsigned, it is implementation defined. The stackoverflow has quote from C99. So when using char, it's better to specify clearly as unsigned char or signed char.

The implementation shall define char to have the same range, representation, 
and behavior as either signed char or unsigned char.

A program to illustrate type conversions, copied from blog.

int main()
{
  signed char c;
  unsigned char uc;
  unsigned short us; // this is *short*

  c = 128;
  uc = 128;

  us = c + uc;
  printf("0x%x\n", us);

  us = (unsigned char)c + uc;
  printf("0x%x\n", us);

  us = c + (char)uc;
  printf("0x%x\n", us);

  return 0;
}

$ ./a.out 
0x0
0x100
0xff00

please note, when left is signed while right is unsigned, the signed left is first promoted to signed right, then to unsigned right. For example in first case, signed c is first promoted to signed short, then to unsigned short, unsigned uc is promoted to unsigned short.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章