C99 标准在 fprintf
(随后适用于 printf
)的规范中讨论了 double。它说“表示 float 的 double
参数被转换......”然后在第 9 段中,它说:
If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding specification, the behavior is undefined.
所以我希望以下是未定义的行为,但我的编译器不会对此发出警告。
double d = 2.0;
float f = 2.0f;
printf("%f", d);
printf("%f", f); // here
另一方面,fscanf
的规范说的是“ float ”而不是 double 。是否像 this user 这样的未定义行为 claim ?
最佳答案
将 float
传递给 printf
不是未定义的行为——这只是不可能的。 float
将在 printf
接收之前提升为 double
。
scanf
不同,因为您(至少通常情况下)传递给 scanf
的是指针,而不是数据对象本身。由于您要传递指向原始数据的指针,因此使用 scanf
您需要区分 float
和 double
。
关于c - 将 float 传递给 printf 是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27495140/