Pregunta

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?

¿Fue útil?

Solución

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;
}

Otros consejos

In this statement

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

you define an object of type int with name printfun that is initialized by the return value of function call display(). It is not a function declaration as you think.

So as printfun is an object of type int then expression

printfun(9);//

has no any sense and the compiler issues an error.

In the second case the code is compiled because function display sees global name printfun that is declared as a function name. printfun inside main is not visible outside main. In fact you use the same name for a local variable defined in main and for global function name that is a function name declared inside the global namespace. Function display sees this global name.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top