How printf works in case of type mismatch with typ

2020-04-21 08:30发布

问题:

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?

回答1:

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.



回答2:

You need to enable that warning.

Compiling your code as test.cpp and adding #include <stdio.h> for printf with the correct warning flag under 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]


回答3:

With printf() if there is a type mismatch then it leads to undefined behavior.

The format specifier should match with the type which you want to print.

Further the number of arguments should match with the number of format specifiers violating which will also leads to undefined behavior.

Just add -Wall while compiling your code you will get the below error:

warning: format %c expects type int, but argument 2 has type char *



标签: c printf