Function prototype declared inside main - best practice?
Is this a good style to have the function prototype declared inside of the main function?
I was looking at a C tutorial, I think is quite out of date. However, they declare the function prototype inside of main. I normally declare outside before main.
#include <stdio.h>
int main ()
{
char myname [30];
int theage;
int getage ();
printf ("\nEnter your name:");
gets (myname);
theage = getage ();
printf("\n AGE = %d and NAME = %s", theage, myname);
return 0;
}
int getage ()
{
int myage; /* local to only getage() */
printf ("\nEnter your age: ");
scanf ("%d",&myage);
return (myage);
}
Solution 1:
I personally would say "no" for several reasons:
- it makes the code for main longer
- it may confuse a newbie into think ing the function is scoped by main
- in real code, I would normally put the function in a different compilation unit and #include its header file
Solution 2:
I'll also say no with the additional reason that if you start using explicit declarations all over the code, you will most definitely get unresolved externals when the function you are calling suddenly changes its signature. If you have ONE declaration in ONE header file, you only need to change ONE declaration when the function changes.
However, I'd say yes because of the following reason: If you are just writing a simple test method that's written for a single use only, i.e. if you want to test something really quick and then discard the function right away. Then it can be nifty to just throw in a declaration right before you want to make the call.
For production code -> No no no ! :)