user8558648
user8558648

Reputation: 41

Why does the function call work even though it is not defined before the call?

I have done this quiz, and do not understand the output

#include <stdio.h>
int main()
{
    void demo();
    void (*fun)();
    fun = demo;
    (*fun)();
    fun();
    return 0;
}

void demo()
{
    printf("GeeksQuiz ");
}

Expected: Compiler error because I thought that normally demo() would need to be initialized before the call in main()?

Actual results: GeeksQuiz GeeksQuiz

Is my assumption wrong that functions generally need to be defined before they can be called?

Upvotes: 1

Views: 67

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

functions generally need to be defined before they can be called

Well, not actually, compiler just needs to see a prototype before the call (usage). A forward declaration would be enough.

In your case, inside main(),

void demo();

is serving that purpose. Note that, this is not a function call.

Upvotes: 6

Related Questions