Search code examples
c++function-prototypes

Function Declaration in C++


I have the below code in CPP.

//My code

#include<iostream>
using namespace std;
int main()
{
    int a;
    int display();
    int printfun(display());// Function prototype
    printfun(9);//Function calling
    return 0;
}
int printfun(int x)

{
    cout<<"Welcome inside the function-"<<x<<endl;
}
int display()
{
    cout<<"Welcome inside the Display"<<endl;
    return 5;

}

Upon compilation it throws an error "Line8:'printfun' cannot be used as a function".

But the same code works perfectly when I make the printfun call inside display function.

#include<iostream>
using namespace std;
int main()
{
    int a;
    int display();
    int printfun(display());// Function prototype
        return 0;
}
int printfun(int x)

{
    cout<<"Welcome inside the function-"<<x<<endl;
}
int display()
{
    printfun(9); // Function call
    cout<<"Welcome inside the Display"<<endl;
    return 5;

}

Could anyone explain the reason behind this?


Solution

  • int printfun(display());// Function prototype
    

    That's not a function prototype. It's a variable declaration, equivalent to:

    int printfun = display();
    

    Function prototypes "can" be done inside main(), but it's much more normal to put them at the top of your source file.

    #include <iostream>
    
    using namespace std;
    
    // Function prototypes.
    int display();
    int printfun(int x);    
    
    int main()
    {
        int a;
        printfun(9);  // Function call.
        return 0;
    }
    
    // Function definitions.
    int printfun(int x)
    {
        cout << "Welcome inside the function-" << x << endl;
    }
    
    int display()
    {
        printfun(9); // Function call.
        cout << "Welcome inside the Display" << endl;
        return 5;
    }