0
  #include <stdio.h>

    int main(void) 
    {

       int i=10;
       printf("%p",i);
       return 0;
    }

output:-

0xa

%p - I have read %p is used to print pointer in printf, but here i is an integer,and also there is no pointer declared so how "0xa" gets output.

  • Wrong input, wrong output. In general, `printf` only prints whatever you put into it. Here you put an integer in it and this integer is printed. As `%p` is not proper format specifier for integer, you also have undefined behaviour – Gerhardh Jun 20 '17 at 09:47
  • By the way, nothing wrong with the question IMHO. Nicely written and a compilable example. – Bathsheba Jun 20 '17 at 10:01

2 Answers2

3

The behaviour of your code is undefined since an %p is not an appropriate format specifier for an int type.

The compiler is allowed to do anything, which includes optimising your code to int main(){}.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

Technically it is undefined behaviour because %p is the wrong format specifier for an int.

But if your platform is 32 bits, then %p usually boils down to printing the supplied value in hexadecimal on most implementations and therefore printf("%p", 10); will usually print 0xA or 0x0000000A on these implementations.

Anyway, don't use unmatched format specifiers, because even if it appears to work, it results in undefined behaviour.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Rationalising UB is a dangerous art. IMHO more care needs to be taken here. E.g. `int` might be 16 bit on a 32 bit platform. What then? But you do describe the output plausibly, so perhaps your answer is more helpful than mine. Have an upvote. – Bathsheba Jun 20 '17 at 09:58
  • @Bathsheba yes `int` might be 16 bits, although I'm not aware of such an implementation. But anyway I wrote _usually_. – Jabberwocky Jun 20 '17 at 09:59
  • Our old friend Turbo C++ has 16 bit ints, and lots of schools seem to use it. – Bathsheba Jun 20 '17 at 10:00
  • Isn't Turbo C++ a 16 bit platform? Maybe I'm wrong. Anyway I really wonder why those schools use Turbo C++ and not gcc or clang. – Jabberwocky Jun 20 '17 at 10:02
  • FWIW, if OP actually wants to get the output he gets, proper formatting would be `"%#x"`. Though care should be taken with signedness. – spectras Jun 20 '17 at 10:21