简体   繁体   English

错误的printf类型仍然打印正确的值

[英]wrong printf types still printing correct values

I just ran into this weird scenario and I just cant explain it. 我刚刚遇到这种奇怪的情况,我无法解释它。 I'm just really curious as to whats happening more than anything. 我真的很好奇,最重要的事情发生了什么。 I have this sample code: 我有这个示例代码:

#include <stdio.h>
#include <stdint.h>

int main()
{
    int64_t qty = 900;
    double  p   = 74.45;

    printf( "%f|%ld\n", p, qty );
    printf( "%f|%ld\n", qty, p );
    return 0;
}

Note that in the second printf I provide the arguments in the WRONG ORDER, not to mention the fact that the types are wrong. 请注意,在第二个printf中,我提供了错误订单中的参数,更不用说类型错误了。 However, I still get the CORRECT output in both? 但是,我仍然得到两个CORRECT输出? How odd is that... Compiling with gcc 7.2: 奇怪的是......用gcc 7.2编译:

$ ./a.out
74.450000|900
74.450000|900

Whats going on here? 这里发生了什么?

Passing the wrong argument types to printf causes undefined behavior. 将错误的参数类型传递给printf会导致未定义的行为。 When you have undefined behavior, anything can happen, including seemingly "correct" behavior. 当您有未定义的行为时,任何事情都可能发生,包括看似“正确”的行为。

In this case, it's most likely that on this architecture integer and floating-point values are passed to variable-argument functions in different registers. 在这种情况下,最有可能的是,在此体系结构中,整数和浮点值将传递给不同寄存器中的变量参数函数。 So printf prints the first floating-point register for %f and the first integer register for %ld , which ends up being correct no matter the order that they were passed in. 因此printf打印%f的第一个浮点寄存器和%ld的第一个整数寄存器,无论它们传入的顺序如何都是正确的。

However, this should never be relied on, and may even give the wrong results on this specific architecture depending on the compiler, optimizations, etc. 但是,永远不应该依赖它,甚至可能在这个特定的体系结构上给出错误的结果,具体取决于编译器,优化等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM