Search code examples
cprintfformat-specifiers

Please explain the difference in the printfs below


printf("%x\n",(const uint8_t *)0x0D);
printf("%x\n",(const uint8_t)0x0D);
printf("%x\n",(uint8_t *)0x0D);
printf("%x\n",0x0D);

They all give me D . What is it the significance of the const and the *s here?


Solution

  • %x format specifier experts the argument to be of type unsigned int.

    In your case,

     printf("%x\n",(const uint8_t)0x0D);
     printf("%x\n",0x0D);
    

    arguments will be promoted (default promotion rule) to match the type, but in case of

     printf("%x\n",(const uint8_t *)0x0D);  //supplying a pointer
     printf("%x\n",(uint8_t *)0x0D);        //supplying a pointer
    

    You'll invoke undefined behavior, as per C11, chapter §7.21.6.1

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