billpcs
billpcs

Reputation: 633

Printing main() in C

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

Answers (5)

humodz
humodz

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

Vikram Singh
Vikram Singh

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

user3328692
user3328692

Reputation: 99

The compiler will display an error.

Upvotes: -1

prashant_jha
prashant_jha

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

unwind
unwind

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

Related Questions