This code
int main() {
printf("%d", square(3));
return 0;
}
int square(int n) {
int sq = n * n;
return sq;
}
relies on the obsolescent feature of implicit function declarations, because there is no declaration of the name square before its usage in main. This feature was removed from the C standard in its 1999 revision. All the most commonly used C compilers still honor it (with warnings) for backward compatibility's sake, but actually using it is bad style and can hide bugs. You should write this program with an explicit "forward declaration" of square above main:
int square(int n);
int main(void)
{
/* remainder of program as you have it */
(Not putting anything at all between the argument parentheses of a function declaration or definition is also an obsolescent feature. To declare or define a function that takes no arguments you have to say (void).)
(In C, for historical reasons, preferred style is to put the opening curly brace of a function definition on its own line, even if all other opening braces are "cuddled" onto the same line as the if, for, etc.)
Having said that, the function square is executed because, in main, it is called:
int main() {
printf("%d", square(3));
^^^^^^
return 0;
}
That is, first main gets control and then inside main the function square is called. If main did not call square, or call a function that calls it, square would never be executed.
The difference between the function main and any other function is that in a host environment the function main contains the entry point to the program that is it gets the control first. And the function main may be defined without the return statement though its return type is int.
mainis called first, and is calling other functions. So eventually the called functions terminate beforemainterminates. - Eugene Sh.main. - melpomene