In C, function pointers and predicates: what does this program print when comparing equal integers? #include<stdio.h> int fun(int, int); typedef int (*pf) (int, int); int proc(pf, int, int); int main() { printf("%d ", proc(fun, 6, 6)); return 0; } int fun(int a, int b) { return (a==b); } int proc(pf p, int a, int b) { return ((*p)(a, b)); }

Difficulty: Easy

Correct Answer: 1

Explanation:


Introduction / Context:
This program demonstrates using a function pointer (pf) to pass a predicate function into another function. The predicate returns 1 when two integers are equal and 0 otherwise. Understanding function pointer invocation is the key here.


Given Data / Assumptions:

  • fun(a, b) returns (a == b), which yields 1 for equal inputs, 0 otherwise.
  • proc takes a function pointer and two ints, and calls the function pointer with those ints.
  • Inputs are (6, 6).


Concept / Approach:
The function pointer call syntax (*p)(a, b) invokes the function denoted by p with the given arguments. Because 6 equals 6, the predicate evaluates to true, represented as integer 1 in C.


Step-by-Step Solution:
Assign p = fun via argument passing to proc.Evaluate (*p)(6, 6) → fun(6, 6) → 1.Return value 1 propagates to main and is printed with %d.


Verification / Alternative check:
Calling fun directly with 6 and 6 yields 1. Changing one argument (e.g., 6 and 5) would print 0, validating the predicate behavior.


Why Other Options Are Wrong:
6, -1 are unrelated to equality checks; 0 would mean the numbers were unequal; undefined behavior does not occur because function pointers and arguments are valid.


Common Pitfalls:
Confusing the equality operator == with assignment =, or misusing function pointer syntax by writing p(a,b) without appropriate declaration (although p(a,b) would also work in C).


Final Answer:
1

More Questions from Functions

Discussion & Comments

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