What will be the output of the following C program?
Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What will be the output of the following C program?
#include <stdio.h>
int change(int (**temp)(int (*)(void)));
int main() {
int change(int (*)(int (*)(void)));
int (*ptr)(int (*)(void)) = change;
printf("%d", (*ptr)(&ptr));
return 0;
}
int change(int (**temp)(int (*)(void))) {
static int m;
if (++m < 10)
(**temp)(temp);
return (m);
}
Show answer & explanation
Answer: A. 10
The program exhibits type mismatch issues that cause undefined behavior leading to output 10. The function change expects int (**temp)(int (*)(void)) (pointer to function pointer), but &ptr of type int (*(*)(int (*)(void))) is passed. The static variable m increments from 1 to 10 across recursive calls before the recursion terminates when m == 10, and the final return value is 10.
Step-by-step Derivation:
Execution trace:
main()declaresptras function pointer tochange- Calls
(*ptr)(&ptr)→change(&ptr)with type mismatch - Inside
change(): static intm = 0(initialized once) - Recursion loop:
++mincrements m, checkm < 10:- m=1: 1<10 → call
(**temp)(temp)→(*ptr)(&ptr)(recursive) - m=2: 2<10 → recurse
- ...
- m=9: 9<10 → recurse
- m=10: 10<10 is FALSE → exit recursion
- m=1: 1<10 → call
- Return m=10 from innermost call; propagates up
printf("%d", 10)outputs: 10