且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 C 中将浮点数打印为整数并将整数打印为浮点数时的奇怪输出

更新时间:2023-11-28 19:56:58

让我们减少一点:

float f = 4.6;
printf("%d\n", f);

这是未定义的行为.必须为正确的格式说明符提供正确类型的参数.

That's undefined behavior. The correct format specifier must be given an argument of the correct type.

未定义的行为可能导致任何结果,包括您所看到的这种奇怪的结果.

Undefined behavior can cause any outcome, including this odd outcome that you are seeing.

现在,您可能会问为什么编译器甚至会生成此代码.那么让我们看看 x86-64 程序集的 2 个代码:

Now, you might be asking why a compiler would even produce this code. So let's look at the x86-64 assembly for 2 codes:

int main() {
    float f = 4.6;
    int d = 7;
    printf("%d %f\n", d, f);
    return 0;
}

int main() {
    float f = 4.6;
    int d = 7;
    printf("%f %d\n", f, d);
    return 0;
}

除了格式字符串,这两个代码产生相同的程序集.这可能是因为调用约定要求将浮点数放置在与整数不同的寄存器中,或者应该将浮点数传递到堆栈中(或任何其他以不同方式处理浮点数和整数的规则).

Other than the format string, these two codes produce identical assembly. This is likely because the calling convention requires floats to be placed in different registers than integers, or that floats should be passed on the stack (or any number of other rules that handle floats and integers differently).

这应该更清楚为什么您发布的代码仍然产生有用的东西,即使代码刚刚损坏.

This should make it clearer why the code you posted is still producing something useful, even though the code is just broken.