如果类型不匹配,printf如何工作?
int main() { printf("%c", "\n"); return 0; }
这里根据类型说明符,需要一个字符。 但我们传递的是const char *
。 我希望它会在代码块GNU GCC编译器中给我一个警告信息,但它没有给我任何警告并打印$
字符。
为什么它没有给出任何类型的警告?
您可以看到代码也适用于%d,%x,%u格式说明符。
为什么它没有任何警告?
因为您的CodeBlocks中没有启用警告。
Go to settings -> compiler and check Enable All Common Compiler Warnings [-Wall]
现在你得到:
In function 'int main()': warning: format '%c' expects argument of type 'int', but argument 2 has type 'const char*' [-Wformat=]|
为什么它甚至有效?
使用%c,$是CodeBlocks中的输出,X是Visual Studio中的输出。 所以,这听起来像未定义的行为。
scanf(或)printf中的格式说明符错误
无论如何,如果你想要这样的第一个char只有你能做到这一点:
#include int main() { printf("%c", *"Hello\n"); // Not asked in Question but still :) return 0; }
它通过取消引用const指针来打印H.
您需要启用该警告。
将您的代码编译为test.cpp
并为printf
添加#include
,并在gcc 4.7.2下添加正确的警告标志:
$ gcc -c -Wformat test.cpp test.cpp: In function 'int main()': test.cpp:5:18: warning: format '%c' expects argument of type 'int', but argument 2 has type 'const char*' [-Wformat]
使用printf()
如果存在类型不匹配,则会导致未定义的行为。
格式说明符应与要打印的类型匹配。
此外,参数的数量应与违反的格式说明符的数量相匹配,这也将导致未定义的行为。
只需在编译代码时添加-Wall
,您将收到以下错误:
警告:格式%c期望类型为int,但参数2的类型为char *