2

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).

Psi
  • 264
  • 3
  • 13

2 Answers2

6

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.

Community
  • 1
  • 1
Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
3

Main is a function like all the rest. Just has a different semantics and different requirements.

The semantics being it is the start of the program.

The requirements it has a predefined set of signatures

Ed Heal
  • 55,822
  • 16
  • 77
  • 115
  • You misunderstood. I am not asking if it is a function, I am asking if the 'main' code can be considered as a function definition. – Psi Jan 09 '17 at 23:46
  • _I was asked if the 'main' function is also considered a function definition or if it is considered as something else_ - I answered this bit – Ed Heal Jan 09 '17 at 23:48
  • You still do not quite follow. I must have phrased it badly. See Jonathan Leffler's post for the answer I was looking for – Psi Jan 09 '17 at 23:59
  • @ThomasHollis-- "Main is a function like all the rest." I believe that the point was that a function is defined when its body is specified, and `main()` is no different in this respect. This answers the question, albeit in a slightly laconic manner. – ad absurdum Jan 10 '17 at 00:18
  • It was rather a bit to the point. Thanks for the expansion of the meaning of the statement – Ed Heal Jan 10 '17 at 00:21