Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is printed when I write function name in C using printf() function

Tags:

c

function

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.

like image 306
Mukit09 Avatar asked Feb 23 '26 00:02

Mukit09


2 Answers

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.

like image 174
unwind Avatar answered Feb 25 '26 18:02

unwind


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.

like image 26
Bathsheba Avatar answered Feb 25 '26 19:02

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!