Bharat Kul Ratan
Bharat Kul Ratan

Reputation: 1003

Difference between main and main()

The following code 1 is fine

#include <stdio.h>    // code 1
main()
{
    printf("%u",main);
}

but this code 2 gives segmentation fault.

#include <stdio.h>  // code 2
main()
{
    printf("%u",main());
}

I'm not getting what's the difference between main and main()?

Upvotes: 0

Views: 1360

Answers (1)

Did you compile with all warnings enabled from your compiler? With gcc that means giving the -Wall argument to gcc (and -g is useful for debugging info).

First, your printf("%u", main) should be printf("%p\n", main). The %p prints a pointer (technically function pointers are not data pointers as needed for %p, practically they often have the same size and similar representation), and you should end your format strings with newline \n. This takes the address of the main function and passes that address to printf.

Then, your second printf("%u", main()) is calling printf with an argument obtained by a recursive call to the main function. This recursion never ends, and you blow up your call stack (i.e. have a stack overflow), so get a SIGSEGV on Unix.

Pedantically, main is a very special name for C standard, and you probably should not call it (it is called auto-magically by startup code in crt0.o). Recursing on main is very bad taste and may be illegal.

See also my other answer here.

Upvotes: 5

Related Questions