问题描述
就printf
函数而言,我从一些参考资料和实验中了解到以下内容.
As of the printf
function is concerned, I understand the following from few references and experiments.
- 当我们尝试使用用于浮点(或)双精度的格式说明符打印整数值时,反之亦然,行为是不可预测的.
- 但是可以使用
%c
打印与整数值等效的字符.也可以使用%d
打印字符的 ASCII 值(整数表示).
- When we try to print an integer value with format specifiers that are used for float (or) double and vice the versa the behaviour is unpredictable.
- But it is possible to use
%c
to print the character equivalent of the integer value. Also using of%d
to print ASCII value (integer representations) of character is acceptable.
同样,如果格式说明符和传递给 scanf 的参数不匹配,scanf
的行为是什么.标准是否定义了它?
Similarly, what is the behaviour of scanf
, if there is a mismatch of format specifier and the arguements passed to scanf. Does the standards define it?
推荐答案
可变参数(那些匹配省略号,...
)是默认提升的.这意味着所有较短的整数类型都被提升为 int
(或无符号,视情况而定).整数和字符之间没有区别(我相信).printf
中 %d
和 %c
之间的区别仅在于值的格式.
Variadic arguments (those matching the ellipsis, ...
) are default-promoted. That means that all shorter integral types are promoted to int
(or unsigned, as appropriate). There's no difference between integers and characters (I believe). The difference between %d
and %c
in printf
is merely how the value is formatted.
scanf
是另一种鱼.您传递的所有参数都是指针.指针之间没有默认的运动,并且传递与指针类型匹配的确切格式说明符至关重要.
scanf
is a different kettle of fish. All the arguments you pass are pointers. There's no default-promotion among pointers, and it is crucial that you pass the exact format specifier that matches the type of the pointee.
在任何一种情况下,如果您的格式说明符与提供的参数不匹配(例如将 int *
传递给 printf
中的 %p
>),结果是未定义行为,这远比不可预测"更糟糕——这意味着你的程序只是格式错误.
In either case, if your format specifier doesn't match the supplied argument (e.g. passing an int *
to a %p
in printf
), the result is undefined behaviour, which is far worse than being "unpredictable" -- it means your program is simply ill-formed.
这篇关于scanf(或) printf 中的格式说明符错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!