c++forward-declarationfunction-definitionfunction-declarationfunction-prototypes

Are function propotypes obsolete in c++


I am looking at an old book and it contains function prototypes. For example:

#include<iostream>
using std::cout;
int main()
{
    int square(int); //function prototype

    for(int x = 0; x<=10; x++)
    {
        cout<<square(x)<<"";
    }

    int square(int y)
    {
        return y * y;
    }

    return 0;
}

However, on newer C++ tutorials, i don't see any function prototypes mentioned. Are they pbsolete after C++98? What are the community guidelines for using them?

Example: https://www.w3schools.com/cpp/trycpp.asp?filename=demo_functions_multiple


Solution

  • For starters defining a function within another function like this

    int main()
    {
        //...
        int square(int y)
        {
            return y * y;
        }
    
        return 0;
    }
    

    is not a standard C++ feature. You should define the function square outside main.

    If you will not declare the function square before the for loop

    int square(int); //function prototype
    
    for(int x = 0; x<=10; x++)
    {
        cout<<square(x)<<"";
    }
    

    then the compiler will issue an error that the name square is not declared. In C++ any name must be declared before its usage.

    You could define the function square before main like

    int square(int y)
    {
        return y * y;
    }
    
    int main()
    {
        //...
    }
    

    In this case the declaration of the function in main

    int square(int); //function prototype
    

    will be redundant because a function definition is at the same time the function declaration.

    What are the community guidelines for using them?

    A function with external linkage if it does not have the function specifier inline shall be defined only once in the program. If several compilation units use the same function then they need to access its declaration.

    In such a case a function declaration is placed in a header that is included in compilation units where the function declaration is required and the function definition is placed in some module.