In C, passing main as a function pointer: what is the program output order? #include<stdio.h> int fun(int(*)()); int main() { fun(main); printf("Hi "); return 0; } int fun(int (*p)()) { printf("Hello "); return 0; }

Difficulty: Easy

Correct Answer: Hello Hi

Explanation:


Introduction / Context:
This program demonstrates passing a function pointer to another function, including passing the address of main itself. The callee prints a message, returns, and then main prints another message. Understanding call order yields the combined output.


Given Data / Assumptions:

  • fun receives a function pointer but does not invoke it.
  • fun prints "Hello " (with a trailing space) and returns.
  • main then prints "Hi\n".


Concept / Approach:
Although main is passed to fun, the function pointer is not used to call main again. Therefore, there is no recursion or infinite loop. The output is simply the concatenation of prints in the order of execution.


Step-by-Step Solution:
Call fun(main) → fun prints "Hello ".Return to main → print "Hi\n".Combined output: "Hello Hi".


Verification / Alternative check:
If fun had called (*p)(), a recursive call to main would occur, potentially leading to repeated outputs. Here, it does not call p.


Why Other Options Are Wrong:
"Infinite loop" would require fun to call p (or main to call itself). "Hi" alone ignores the first print. "Error" is incorrect—the code is valid in C. "Hi Hello" reverses the actual order.


Common Pitfalls:
Assuming that passing main necessarily means recursion. It only happens if the pointer is actually invoked.


Final Answer:
Hello Hi

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion