是否printf()的依赖于格式说明符的顺序? [英] Does printf() depend on order of format specifiers?

查看:219
本文介绍了是否printf()的依赖于格式说明符的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
main()
{
    float x=2;
    float y=4;
    printf("\n%d\n%f",x/y,x/y);
    printf("\n%f\n%d",x/y,x/y);
}

输出:

0 
0.000000
0.500000 
0

用gcc 4.4.3编译
错误code退出程序12

compiled with gcc 4.4.3 The program exited with error code 12

推荐答案

在其他的答案指出,这是因为格式字符串和参数的类型之间的不匹配。

As noted in other answers, this is because of the mismatch between the format string and the type of the argument.

我猜你正在使用的x86这里(根据观测结果)。

I'll guess that you're using x86 here (based on the observed results).

该参数在栈中传递,而 X / Y ,虽然类型的浮动,将被传递作为双击来一个可变参数函数(由于输入促销规则)。

The arguments are passed on the stack, and x/y, although of type float, will be passed as a double to a varargs function (due to type "promotion" rules).

这是 INT 是一个32位的值,和双击是一个64位值。

An int is a 32-bit value, and a double is a 64-bit value.

在这两种情况下,你是路过 X / Y (= 0.5)的两倍。这个值的重新presentation,作为一个64位的双击 0x3fe0000000000000 。作为一对32位字,它存储为 00000000 (至少显著32位),然后按 0x3fe00000 (最显著32位)。因此,在堆栈上的参数,由的printf所看到(),是这样的:

In both cases you are passing x/y (= 0.5) twice. The representation of this value, as a 64-bit double, is 0x3fe0000000000000. As a pair of 32-bit words, it's stored as 0x00000000 (least significant 32 bits) followed by 0x3fe00000 (most significant 32-bits). So the arguments on the stack, as seen by printf(), look like this:

0x3fe00000
0x00000000
0x3fe00000
0x00000000  <-- stack pointer

在第一个的两种情况,%d个导致前32位的值, 00000000 ,被弹出并打印。在%F 弹出接下来的两个32位值, 0x3fe00000 (64位中至少有显著32位双击),其次是 00000000 (最显著)。 0x000000003fe00000 的产生的64位值,除preTED为双击,是一个非常小的数目。 (如果你改变了%F 格式字符串%G 你会看到它的几乎为0,但不大)。

In the first of your two cases, the %d causes the first 32-bit value, 0x00000000, to be popped and printed. The %f pops the next two 32-bit values, 0x3fe00000 (least significant 32 bits of 64 bit double), followed by 0x00000000 (most significant). The resulting 64-bit value of 0x000000003fe00000, interpreted as a double, is a very small number. (If you change the %f in the format string to %g you'll see that it's almost 0, but not quite).

在第二种情况下,%F 正确弹出第一个双击%d个弹出 00000000 第二的一半双击,所以它似乎工作

In the second case, the %f correctly pops the first double, and the %d pops the 0x00000000 half of the second double, so it appears to work.

这篇关于是否printf()的依赖于格式说明符的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆