在处理一个从二进制文件中读取结构数据类型的简单项目时,我遇到了一个奇怪的 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/