3

When I'm writing this code:

#include <stdio.h>

int main()
{
    printf("%p\n",main);
    printf("%d\n",main);
    return 0;
}

my compiler shows me this output:

00401318
4199192

I'm interested to know what actually is printed. I googled my question, but have found nothing. :(

Thanks in advance.

Mukit09
  • 2,956
  • 3
  • 24
  • 44

2 Answers2

5

This is not well-defined.

You're using %p, which expects an argument of type void *, but you're actually passing it a value of type int (*)(), i.e. your (also badly defined) main() function.

You cannot portably cast a function pointer to void *, so your code can never be correct.

On most typicaly systems, sizeof (void *) == sizeof main, so you simply get the value interpreted as a void * which probably will simply be the address of the function.

Passing a function address to printf() with a format specifier of %d is even worse, since it's quite likely that sizeof (int) != sizeof main and then you get undefined behavior.

This is not good code.

unwind
  • 391,730
  • 64
  • 469
  • 606
4

main is a function pointer of type int(*)(void)

  1. printf("%p\n", main);

You are printing the address of that pointer, which, on your platform has been successfully cast to a void*. This will be fine if sizeof(main) == sizeof(void*).

  1. printf("%d\n", main);

This will give you undefined behaviour since %d is not a good format specifier for a pointer type.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • What's about %d specifier ? – Mukit09 Dec 10 '14 at 14:50
  • OP is printing **the value** of the pointer (which is the address of the function), not **the address** of the pointer. In addition, the second call to `printf` is guaranteed to work correctly only if `sizeof(void*)` is equal to `sizeof(int)` on OP's platform, but it is generally considered as undefined behavior. One last thing - I'm not the one who downvoted you for this answer, so please don't go around downvoting random answers of my own. – barak manos Dec 10 '14 at 14:51
  • They are the same values. `%p` formats it as hex, and `%d` formats as decimal. `0x401318 == 4199192` – robert Dec 10 '14 at 14:52
  • @robert: That's not true. For example, if OP is running on a 64-bit platform (64GB memory address space), then `%p` would be equivalent to `%lld` (or more precisely, to `%llx`). – barak manos Dec 10 '14 at 14:57
  • OK. In any case, I still think you're wrong with "the address of that pointer". – barak manos Dec 10 '14 at 14:59
  • 1
    Downvoted for *"`%p` should be fine though"*. Function pointers are not compatible with `void*` pointers. – user694733 Dec 10 '14 at 15:16
  • Flogged this once more. – Bathsheba Dec 10 '14 at 15:28