考虑这个计划如何在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