dark_shadow
dark_shadow

Reputation: 3573

Can anyone please explain the output of C program?

I found this problem in a book.

Problem:

What is the output of the following program ?

#include <stdio.h>
int fun(int,int);
typedef int(*pf) (int,int);
int proc(pf,int,int);

int main()
{
    printf("%d\n",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));
}

This code, when run, prints out 1.

I tried understanding it but no it is of no use. What is going in this program and why does it output 1?

Thanks in advance.

Upvotes: 0

Views: 1442

Answers (3)

Vijay
Vijay

Reputation: 67211

int fun(int,int); 

function takes 2 int arguments and returns an int

typedef int(*pf) (int,int); 

pf is a function pointer that store the address of address of a function which takes two ints as its agrs and returns an int

int proc(pf,int,int); 

proc is a function which takes 3 args first is a function pointer to a function like above and two integer args.

proc(fun,6,6);

above statement calls fun with two args 6 and 6 and returns true if they are equal which is how the result is 1

Upvotes: 0

Habib
Habib

Reputation: 223187

In main the first line

printf("%d\n",proc(fun,6,6));

is calling proc which is taking argument a function pointer and two integer values. Function pointer pf is defined as typedef int(*pf) (int,int); This line printf("%d\n",proc(fun,6,6)); will call the function defined as:

int proc(pf p,int a,int b){
return ((*p)(a,b));
}

Now in this function pf holds the pointer to function fun. This will cause the function fun to be called which is returning whether the values of a and b are true or not. Since you have passed 6,6 as the arguments the result will be true and that is why you are getting as 1 as an Answer.

Upvotes: 1

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43498

proc is indirectly calling fun via a function pointer. The arguments that fun receives are again 6 and 6, and the equality operator evaluates to an int with the value 1 because they are equal. If they were not equal, the == operator would yield 0.

Upvotes: 2

Related Questions