Can't define a function within the main function?


#1

Hi,

Basic question here. I just finished chapter 5 and now I’m experimenting with creating some functions on my own to get the hang of it.

Is it the case that you cannot create a function within the main function? So, all functions must be defined above main() and only called within main?

Thanks! Great book by the way.


#2

In all the programs (at least in C-style languages) the program execution begins in the main() function, that’s where all start.

As you said, the functions are only called within main(), why? because there is where the program run.

So, if you write an x function above main(), the compiler knows that x function exists, and at the time the compiler arrives at your main() function (remember that the compiler reads your programs in an up-down pattern) the compiler knows what function is being called within main() (in this case,your x function).

Imagine if you got another function (y function), but the code for that function is below main(), the compiler won’t know what is y function, so you will have a compilation error, but there’s a solution to that, if you want to write the code for your y function below main(), just declare the function above main() and write the code (initialize) for that function below main(), in that way, the compiler knows that there exist a function in memory called y, before arriving to the main() function.

This is an example (this program will run):

#include <stdio.h>

void additionOfThreeNumbers();


int main(int argc, const char * argv[]) {

additionOfThreeNumbers(7,10,4);

return 0;
}


void additionOfThreeNumbers(int a, int b, int c)
{
int total = a + b + c;
printf("The sum of %d and %d and %d is %d\n", a, b, c, total);
}

This won’t:

#include <stdio.h>

int main(int argc, const char * argv[]) {

additionOfThreeNumbers(7,10,4);

return 0;
}


void additionOfThreeNumbers(int a, int b, int c)
{
int total = a + b + c;
printf("The sum of %d and %d and %d is %d\n", a, b, c, total);
}