In the C++ language, is it legal to put function prototypes inside of main
or another function? Is this bad practice? Why would someone put prototypes inside of main?
Yes, it is legal - there is no doubt about that. It is usually not advisable, though.
One reason that it isn't advisable is that the function is then only available (as a result of that declaration) in that particular function; other functions in the same file cannot make use of that declaration (but the other functions might contain their own declaration of the function - but then you're repeating yourself, which isn't a good idea).
Additionally, you lose the primary benefit of cross-checking. The best way to do it is:
static
or the anonymous namespace, or in the appropriate other namespace), and ensure it is either defined or declared before it is used.This way, if you need to change the function declaration, you have fewer places to track down. If you have the function declared in multiple places, you have to change all the declarations at once. Of course, for a radical enough change (extra arguments, or fewer arguments) you will have to modify the calls to the function; for other changes (such as adding a const
qualifier to an argument, or changing from pass-by-value to pass-by-reference), you may not need to change anything in the source; a simple recompile may be sufficient.