当我使用了错误的格式说明会发生什么? [英] What happens when I use the wrong format specifier?
问题描述
只是想知道,当我使用了错误的格式说明用C会发生什么?
例如:
X ='A';
的printf(%C \\ n,x)的;
的printf(%d个\\ N,X);X = 65;
的printf(%C \\ n,x)的;
的printf(%d个\\ N,X);X = 128;
的printf(%d个\\ N,X);
当我使用C中的错误格式说明会发生什么情况?
块引用>一般来说,不确定的行为。 *
不过,记得
的printf
是一个可变参数函数,并且参数参数可变型函数经历的默认参数提升的。因此,例如,一个字符
被提升到一个INT
。因此,在实践中,这些都将得到同样的结果:字符X ='A';
的printf(%C \\ n,x)的;INT Y ='A';
的printf(%C \\ N,Y);而这是不确定的行为:
长Z ='A';
的printf(%C \\ N,Z);
<子> *见例如部分C99标准的7.19.6.1 P9:
如果任一参数
不正确的类型对应的转换规范,行为
未定义。
块引用>Just wondering what happens when I use the wrong format specifier in C?
For example:
x = 'A'; printf("%c\n", x); printf("%d\n", x); x = 65; printf("%c\n", x); printf("%d\n", x); x = 128; printf("%d\n", x);
解决方案what happens when I use the wrong format specifier in C?
Generally speaking, undefined behaviour.*
However, recall that
printf
is a variadic function, and that the arguments to variadic functions undergo the default argument promotions. So for instance, achar
is promoted to anint
. So in practice, these will both give the same results:char x = 'A'; printf("%c\n", x); int y = 'A'; printf("%c\n", y);
whereas this is undefined behaviour:
long z = 'A'; printf("%c\n", z);
* See for example section 7.19.6.1 p9 of the C99 standard:If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
这篇关于当我使用了错误的格式说明会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!