考慮這個計劃如何在printf中處理float/double轉換爲int?
int main()
{
float f = 11.22;
double d = 44.55;
int i,j;
i = f; //cast float to int
j = d; //cast double to int
printf("i = %d, j = %d, f = %d, d = %d", i,j,f,d);
//This prints the following:
// i = 11, j = 44, f = -536870912, d = 1076261027
return 0;
}
有人可以解釋爲什麼從雙/浮到INT鑄造正常工作在第一種情況下,和在printf中完成時不起作用?
該程序是在32位Linux機器上的gcc-4.1.2上編譯的。
編輯: Zach's answer似乎是合乎邏輯的,即使用格式說明,以弄清楚如何彈出堆棧。然後考慮這個後續問題:
int main()
{
char c = 'd'; // sizeof c is 1, however sizeof character literal
// 'd' is equal to sizeof(int) in ANSI C
printf("lit = %c, lit = %d , c = %c, c = %d", 'd', 'd', c, c);
//this prints: lit = d, lit = 100 , c = d, c = 100
//how does printf here pop off the right number of bytes even when
//the size represented by format specifiers doesn't actually match
//the size of the passed arguments(char(1 byte) & char_literal(4 bytes))
return 0;
}
這是如何工作的?
我有類似的疑問。看到這個線程:http://stackoverflow.com/questions/2377733/how-does-this-program-work – Lazer 2010-03-08 03:16:14
字符是一個單一的字符 - 它只是一個8位整數。當你對整型小於int的任何類型的操作時,它們會被提升爲整數。這包括調用函數時。所以實際上它不是隨機的機會導致你的printf調用工作,這種行爲是定義的。 實際上,在大多數C ABI中,您始終爲堆棧上傳遞的每個變量分配至少一個機器字。 – 2016-01-22 16:00:04
@SurajJain是,''參數傳遞只考慮根據默認參數促銷推廣的類型(C11§6.5.2.2/ 6,§7.16.1.1/ 2),它確保'char'和'int'兼容。然而,這與用於算術的促銷不完全相同。另外,就ABI而言,推斷語言是很危險的。確認它確實需要檢查規則。 –
Potatoswatter
2016-08-23 05:04:26