Search code examples
cfunction-declaration

Is the 'main' function classified as a function definition in C?


Is the 'main' function classified as a function definition in C?

The reason I am asking is I have been presented with a piece of code and when explaining the difference between the function declarations at the top of the code and the function definitions at the bottom, I was asked if the 'main' function is also considered a function definition or if it is considered as something else (as main functions are essential unlike other functions).


Solution

  • In a hosted implementation of C (the normal sort), the only novel features of main() compared to any other function are:

    • It is where the program execution starts.
    • It does not have to be pre-declared.
    • If execution reaches the } at the end, it behaves as if there was a return 0; before the }*.

    In all other respects, main() is a normal function. It can be called recursively in C (whereas a C++ program cannot call its main() recursively).

    Since a function is defined when its body is specified, when you write int main(void) { … } or int main(int argc, char **argv) { … } or any alternative, you are defining the function because the braces are present so the function body is defined.

    * See What should main() return in C and C++ for some minor caveats about the return 0; statement if the return type is not compatible with int.