Reputation: 633
So I got this small block of code .The main function printing the main function. What does it print ? Is it some sort of address ?
int main() {
printf( "%d", main ) ;
}
Upvotes: 1
Views: 6869
Reputation: 602
Assuming a function fn()
printf("%d",fn());
Will print its return value as a decimal int. The compiler will probably complain if it returns something that is not an int.
printf("%d",fn);
Will print its address as an int. The compiler may complain about the function pointer-to-int conversion.
The correct way to print an address is:
printf("%p",variable);
EDIT: However, as Pascal and others mentioned, %p is only valid for pointers to objects, so there's no correct way of printing the adress of functions.
Upvotes: 0
Reputation: 958
This will print the address of the function main() but in decimal format.You should use %x instead of %d. When compiler compiles a program it creates many memory segment but all the code goes into the .text segment which is a read only segment. So this address is from .text segment. try writing to this address, you should get an error.
Upvotes: -1
Reputation: 11
it will print the address of main. It is as simple as you are trying to print the address of any normal function.
Upvotes: -1
Reputation: 399753
Yes, the name of a function evaluates to its address. Without the function-call operator ()
, no call is made.
But this is not valid code, %d
is not a valid format specifier for a function pointer (and the return
is missing). Unfortunately, printing a function pointer is not very simple to get right.
Upvotes: 5