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?
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:You need to enable that warning.
Compiling your code as
test.cpp
and adding#include <stdio.h>
forprintf
with the correct warning flag under gcc 4.7.2: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.
And now you get:
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:
It prints H by dereferencing the const pointer.