2016-12-22 272 views
-4

我已經通過自學了C了,我覺得%ld可以用於更長的號碼,我不知道爲什麼有%d,而對於更短的一個,%hd還是類似的?如果有%ld或甚至%lld,爲什麼我們要使用%d甚至%hd?

我也想知道C說明符是如何工作的,爲什麼我們需要不同範圍的數值數據類型的不同說明符,因爲每種數據類型都有限制範圍?

+0

Google it。你會得到答案。 – MayurK

+1

當你傳遞一個int時,你可以使用'%d'來打印'int';當你通過一個'long'時使用'%ld',當你通過'long long'時使用'%lld'。你可以使用'%hd'將範圍限制爲'short'的範圍。在打印之前,「int」將被轉換爲「short」。 –

+0

非常感謝,我現在得到它 –

回答

0

通過外觀你正在談論打印功能?或者採用類似參數的其他功能。

它與原始類型有關,例如: int可以保存小於16位的數字。 作爲long可以保存32位。 然後有一個long long可以保存64位。

這一切都取決於你正在使用的原語,很容易找到原語持有多少位。您還必須小心使用它們的時間和地點,因爲用戶可能沒有足夠強大的計算機來運行它。還有一些事實是,某些版本的C可能沒有特定的基元,這可能會降低到甚至優化修改後的C系統。

0

考慮printf(const char *format, ...)在格式和任意數量的值之後取任意類型。 int通常佔用的空間少於long long

printf()使用format來確定後面的參數。如果說明符不匹配傳遞的類型,則爲未定義的行爲。

long long ll = 12345678; 
int i = 4321; 
printf("%lld %d\n", ll, i); // Format matches the type and count of arguments passed. 
          // Result: values printed as text as expected 
printf("%d %d %d\n", ll, i); // Format mis-matches the type and count of arguments 
          // Result: undefined behavior 

"%hd""%hdd"涉及另一種機制。 C很早以前決定在使用像shortsigned char這樣的小型號時,在進一步處理(存在一些例外)之前,他們將首先穿過整數促銷int。因此,對於像printf()這樣的函數,當傳遞short時,首先將該值轉換爲intprintf()不知道它收到的int最初是int還是short。在這種情況下,以下是確定的。

int i = 4321; 
short s = 321; 

printf("%hd %d\n", i, i); // Format matches the promoted type 
printf("%hd %d\n", s, s); // Format matches the promoted type 

printf()遇到"%hd",它希望收到int,但它會在內部轉換是int值在打印之前short值。