如果类型与类型说明符不匹配,printf 如何工作? [英] How printf works in case of type mismatch with type specifier?

查看:68
本文介绍了如果类型与类型说明符不匹配,printf 如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main(){printf("%c", "\n");返回0;}

这里根据类型说明符需要一个字符.但是我们正在传递它const char *.我希望它会在代码块 GNU GCC 编译器中给我一条警告消息,但它没有给我任何警告并打印 $ 字符.

为什么它没有给出任何类型的警告?

解决方案

您可以看到该代码也适用于 %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.

这篇关于如果类型与类型说明符不匹配,printf 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆