Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 796
Vinoth Karthick Avatar asked Feb 10 '26 23:02

Vinoth Karthick


1 Answers

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;
}
like image 71
John Kugelman Avatar answered Feb 13 '26 15:02

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!