類型之間的轉換:程序員
int main() { long l = 800; int i = (int) l; return 0; }
int main() { int i = 280; char a = i; return 0; }
強制類型轉換的結果:函數
注意: 並非全部的類型都能進行強制轉換
例子:3d
#include <stdio.h> struct TS { int i; int j; }; struct TS ts; int main(int argc, char const *argv[]) { short s = 0x1122; char c = (char)s; // 0x22 int i = (int)s; // 0x00001122 int j = (int )3.1415; // 3 unsigned int p = (unsigned int )&ts; // long l = (long )ts; // error // ts = (struct TS)l; // error printf("s = %x\n",s); printf("c = %x\n",c); printf("i = %x\n",i); printf("j = %x\n",j); printf("p = %x\n",p); printf("&ts = %p\n",&ts); return 0; }
結果:
code
隱式類型轉換
編譯器主動進行的類型轉換blog
隱式類型轉換的發生點編譯器
#include <stdio.h> int main(int argc, char const *argv[]) { char c = 'a'; int i = c; unsigned int j = 0x11223344; short s = j; printf("c = %c\n",c); printf("i = %d\n",i); printf("j = %x\n",j); printf("s = %x\n",s); printf("sizeof(c+s) = %d\n",sizeof(c+s)); return 0; }
結果:
io
注: 標準的C語言編譯器的類型檢查是比較寬鬆的,所以
隱式類型轉換可能帶來意外的錯誤。編譯