各種資料型別的取值範圍(自查)
阿新 • • 發佈:2019-01-29
在寫程式的過程中我們有時候會處理一些極大地資料,這時候就會出現一些困惑各種資料型別的大小,宣告的時候讓自己很謹慎, 於是碰到較大的數值就直接long型別的的變數就聲明瞭,在C函式庫Limits中包含著對於所用編譯器中各個資料型別的取值範圍。下面是程式程式碼。
/*本程式中得到啟示:在輸出不同型別的資料時,輸出格式也要相應改變 * long型別的要新增‘l’,unsigned要新增'u'否則會發生越界*/ #include <limits.h> #include <stdio.h> int main() { printf("The Bits Of Type Char: %d \n",CHAR_BIT); printf("The Max Of Char: %d \n",CHAR_MAX); printf("The Min Of Char: %d \n",CHAR_MIN); printf("The Max Of Int: %d \n",INT_MAX); printf("The Min Of Int: %d \n",INT_MIN); printf("The Max Of Long: %ld \n",LONG_MAX); printf("The Min Of Long: %ld \n",LONG_MIN); printf("The Max Of Short: %d \n",SHRT_MAX); printf("The Min Of Short: %d \n",SHRT_MIN); printf("The Max Of unsigned Char: %u \n",UCHAR_MAX); //此處如果是%d,會顯示越界 printf("The Max Of unsigned Int: %u \n",UINT_MAX); printf("The Max Of unsigned Short: %u \n",USHRT_MAX); //此處如果是%d,會顯示越界 printf("The Max Of unsigned Long: %lu \n",ULONG_MAX); return 0; }
這是我自己的電腦windows32位機的執行結果。
通過上圖可以發現int與long的數值範圍是一致的,因為在32位作業系統中,int跟long都佔4位元組,char佔1個位元組,short佔兩個位元組。數值最大取值為1000000000(<2147483647),在32位系統中時完全不會越界的。(平時都被一些極為老式的教科書上說的int佔2個位元組宣告為unsigned最大才為65535給蒙了)。