C Programming - Functions - Discussion

Discussion Forum : Functions - Find Output of Program (Q.No. 18)
18.
What will be the output of the program?
#include<stdio.h>
int fun(int(*)());

int main()
{
    fun(main);
    printf("Hi\n");
    return 0;
}
int fun(int (*p)())
{
    printf("Hello ");
    return 0;
}
Infinite loop
Hi
Hello Hi
Error
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
33 comments Page 1 of 4.

Suraj said:   6 years ago
Thanks for the valuable information @Govind.

Giridhar said:   6 years ago
Pointer function "*p() " which is referring to main is not invoking in "fun(int (*p) ()) ". So, the main() function is not invoked in recursive.

Ram said:   7 years ago
Is this the correct way of passing any function into another function? Please explain.

Amruta said:   8 years ago
int (*p) () p is a function pointer which should point to a function taking no args and returning int.

Nagu said:   8 years ago
Why the infinite loop not exist when main was used?

The infinite loop does not exist because of the sub-function not recursive function so not infinite loop exists.

The sub-function print "hello" then come to the main function. Then print "hi" end the program.

So not confusing the pointer argument that only pass main program address that not used in sub-function.

Thanks.

Karthik said:   8 years ago
Why the infinite loop not exist when main was used?

Niharika said:   9 years ago
As main call go there will recursion and no output.

Robert said:   9 years ago
Both fun and main are returning integers data types.

int(*p)() = a pointer to a function
Since we can treat a function name like a pointer holding its address so we can access it :

int(*p)() = main (where remember int(*p)() is a pointer to a function and main is also a pointer to the address of function main)

The "main" the argument of the fun is not used in any statement here, thereby it goes with the execution of fun() => the body of the fun will be executed untouched => prints Hello => gives back control to the main function via return 0.
In the main function, after the body of fun() got executed and it returns => prints Hi and exits => answer Hello Hi.

Aritra said:   9 years ago
@Govind.

Your explanations are really helpful. Thanks a lot.

Govind said:   9 years ago
Please, can anyone explain fun(main) will not go for infinite?


Post your comments here:

Your comments will be displayed after verification.