Search code examples
cprintfformat-specifiersformat-string

can someone explain me why when a "string" is used with the "%d" fromat specifier it gives strange output


Here's the program:

#include <stdio.h>
main()
{
  printf("%d", "A"); // Can i know what the output from "printf" even means why the output is so strange

} // this outputs: "4214884" in my compiler

As you see the output is so strange and can anyone of you explain this to me. Is this undefined behavior? Is this behavior described anywhere in the C standard so I can read about it


Solution

  • Yes, this is undefined behaviour. %d expects the argument to be an integer, here what you pass is the address of the first element of a string literal, which is a pointer type.

    As per C11, chapter 7.21.6.1/P9

    [...]If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

    That said, for a hosted environment, main() should be int main(void).