c++ - printf - 奇怪的类型混搭结果。有人可以解释一下吗?

标签 c++ c struct printf

在处理一个从二进制文件中读取结构数据类型的简单项目时,我遇到了一个奇怪的 printf 格式类型混杂。基本上我大部分时间都使用 %u 格式来显示无符号整数,而在我的结构中是一个类型为 unsigned long long 的成员,以格式显示此数据字符会导致一些奇怪的情况,并且会浪费几个小时来寻找错误类型。

这是一个例子:

struct bar {
    unsigned long long ll;
    unsigned int i1;
    unsigned int i2;
};

int main(void)
{
    bar fubar;
    fubar.ll = 1200;
    fubar.i1 = 2500;
    fubar.i2 = 450;

    printf("Debt: %u Euro, Wallet: %u Euro, Outgoings: %u Euro.\n", fubar.ll, fubar.i1, fubar.i2);

    return 0;
}

结果:

Debt: 1200 Euro, Wallet: 0 Euro, Outgoings: 2500 Euro.

Compiled with Visual Studio 2013.

当然,当我使用 %llu 格式时,一切都按预期进行。

这是由于 printf 的工作方式和实现方式造成的吗?

最佳答案

unsigned long long 将使用 %llu 打印。使用不匹配类型的变量会调用未定义的行为。

引用 C11,章节 §7.21.6.1

ll (ell-ell)

Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long long int or unsigned long long int argument;

关于 UB,

[..] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

关于c++ - printf - 奇怪的类型混搭结果。有人可以解释一下吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32405505/

相关文章:

c - `char *array[size]` 和 `extern char **array` 的错误链接?

c++ - C++存储模板结构

c++ - 对结构数组的成员排序后,移动结构数组的其余成员

c++ - 如何在 OpenGL(GLUT) 场景中创建静态背景图像?

c++ - C++-为脱机VS2013加载Microsoft符号

c++ - 如何更改静态链接库中常量字符串数组的 Visual Studio C++ 初始化顺序

c - 将 char 的 int 值保存到 int 变量中

c++ - 在 g++ 中使用 __attribute__ 的不平衡括号

swift - 使用 Struct 传递变量 Swift

c++ - 在 C++ 中模拟编译时反射