Search code examples
c++function-prototypes

Is it legal to put function prototypes inside of main or another function?


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?


Solution

  • 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:

    • If the function is defined in the same source file (and not used outside the source file), then limit its scope to the file (static or the anonymous namespace, or in the appropriate other namespace), and ensure it is either defined or declared before it is used.
    • If the function is defined in a different source file, there should be a header that declares the function. Include the header in both the file that defines the function (to ensure that the declaration in the header is consistent with the definition) and in the files that use the function.

    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.