[关闭]
@nrailgun 2015-10-01T14:38:22.000000Z 字数 1392 阅读 1436

C Type Casting

程序设计


C is a low level language, which processes memory (variable) directly. When you are working with hardware or network / transmission protocol, you have to deal with signed or unsigned bytes, integers often.

It's usual to perform calculation on different size integers or different signedness integers. Problems happen here. Misunderstanding of C type casting keeps making troubles.

Promotion and Conversion

When arithmetic operations are performed on 2 different type operands, integeral promotions are performed first. Integeral promotions converts integer type smaller than int or unsigned int to int or unsigned int. If operands still have different type, following conversions will be performed.

Created with Raphaël 2.1.2intunsigned intlongunsigned longfloatdoule

Wrap Around

What will happen I decide to assign a value out of range to a variable? If the variable is unsigned, wrap around will happen. Only lower bits will be kept (C++ Primer says C++ keeps modules. I think it is the same).

If the variable is signed, it's compiler dependent. But usually the same as unsigned. I tested on Linux with gcc, and it turn out to be the same. C and C++ simply strip higher part off.

By the way, what shocked me(Jesus christ! I thought it was for certain!):

Selecting the MSB or LSB as signness bit is Compiler dependent.

Confusing cases

  1. #include <stdio.h>
  2. int main(void)
  3. {
  4. unsigned char a = 0xff;
  5. char b = 0xff;
  6. int c = a == b; // true or false?
  7. printf("C: %d\n", c);
  8. return 0;
  9. }

Now, you should know: a == b first cast a to unsigned int (which is 0x000000ff), and b to int (which is 0xffffffff), then cast both to unsigned int. Of course, a == b is false.

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注