且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果类型与类型说明符不匹配,printf 如何工作?

更新时间:2023-02-21 23:03:43

您可以看到该代码也适用于 %d、%x、%u 格式说明符.

为什么它可以在没有任何警告的情况下工作?

因为您的 CodeBlocks 中没有启用警告.

转到设置->编译器和检查启用所有常见的编译器警告 [-Wall]

现在你得到:

在函数int main()"中:警告:格式 '%c' 需要类型为 'int' 的参数,但参数 2 的类型为 'const char*' [-Wformat=]|

为什么它甚至有效?

对于 %c,$ 是 CodeBlocks 中的输出,X 是 Visual Studio 中的输出.所以,这听起来像是未定义的行为.

scanf(或)printf 中的格式说明符错误>

无论如何,如果你想要第一个字符,你只能这样做:

#include int main(){printf("%c", *"你好\n");//没有在问题中提出,但仍然:)返回0;}

它通过取消引用 const 指针来打印 H.

int main()
{
printf("%c", "\n");

return 0;
}

Here according to type specifier a character is required. But we are passing it const char *. I was hoping that it would give me a warning message in code blocks GNU GCC compiler but it is not giving me any warning and printing the $ character.

why it is not giving any type of warning?

You could see that the code also works with %d, %x, %u format specifiers.

Why it works without any warnings ?

Because you don't have warnings enabled in your CodeBlocks.

Go to settings -> compiler and check

Enable All Common Compiler Warnings [-Wall]

And now you get:

In function 'int main()':
warning: format '%c' expects argument of type 'int', but argument 2 has type 'const char*' [-Wformat=]|

Why it even works ?

With %c, $ is the output in CodeBlocks, X is the output in Visual Studio . So, that sounds like undefined behavior.

Wrong format specifiers in scanf (or) printf

Anyways if you want the first char this way only you could do this:

#include <stdio.h>

int main()
{
printf("%c", *"Hello\n"); // Not asked in Question but still :)

return 0;
}

It prints H by dereferencing the const pointer.