c - 将 float 传递给 printf 是未定义的行为吗?

标签 c printf

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 您需要区分 floatdouble

关于c - 将 float 传递给 printf 是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27495140/

相关文章:

assembly - 在 MASM 中调用 c 的 print

C Treenode 指针用全局变量改变值

c - c 的头文件中带有指向它的指针的结构问题

c - 是什么导致段错误?

c - 在 C 中将模板字符串中的\b 处理为 printf

c - C 中的二进制表示

perl - 如何使用 printf 和 Perl 的 Term::ANSIColor 获得彩色输出?

c - 我如何在单行上打印数字

C - 带有嵌套 fgets 循环的 fork 和管道

c - 编译 .c 代码时未声明 socklen_t