Which one of the given options is correct with respect to the return statement of the...
Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Which one of the given options is correct with respect to the return statement of the function declaration given below?
int h (int (* p)(int, int), int x, int y);
Show answer & explanation
The function h takes a function pointer p that accepts two integers and returns an integer, along with two integer parameters x and y. To invoke the function pointed to by p and return its result, we must dereference the pointer and call it with the correct arguments: (* p) (x, y). This dereferences the pointer to get the function, then calls it with x and y as arguments, returning the integer result.
Step-by-step Derivation:
Analyze the function signature:
int h (int (* p)(int, int), int x, int y);- Return type:
int - Parameter
p: pointer to a function that takes twointarguments and returnsint - Parameters
x,y: two integers
- Return type:
Evaluate each option:
- A)
return *p;— Dereferences the function pointer but doesn't call it. Returns a function pointer (type mismatch; function pointers cannot be directly returned asint). - B)
return (* p) (x, y) (*x, *y);— Syntax error. Attempts to call the result of(* p) (x, y)with(*x, *y), which is invalid. Also,*xand*ydereference integers (meaningless). - C)
return 0;— Valid but ignores the function pointer and parameters entirely; not the intended use. - D)
return (* p) (x, y);— Dereferencespto get the function, calls it with argumentsxandy, and returns the integer result. Matches the function's return type.
- A)
Correct answer: D — This is the only syntactically correct and semantically appropriate way to invoke the function pointed to by
pand return its result.