Open Source Technical Information: typedef with With Pointer To Function .

Friday, 21 October 2011

typedef with With Pointer To Function .

,
What is the output of the following program ?
int f(int,int);
typedef int (*pf)(int,int);
int proc(pf,int,int);
 int main()
{
          printf("%d\n",proc(f,6,6));
           return(0);
}
int f(int a,int b)
{
           return(a==b);
}
int proc(pf p,int a,int b)
{
           return((*p)(a,b));
}
 Output will be 1:
Explanation :- Line By Line
1. int f(int,int); ---->
This is the simply a function declaration named by "f" and whose return type is int and argument is int and int datatype....

2. typedef int (*pf)(int,int);---->
this is the critical section of this program ....wt does is means.? ..its mean that we are trying to point a function via a "pf" that will take two argument of int type and return a value of int type ... and there is also a " typedef " which announced that in future we can create variable , pointer etc...of " pf type " means a variable or pointer which point a function whose argument are 2 int datatype and return a int data type .....if you understand this line then whole mystery get solved automatically ...
let move on 3rd line

3. int proc(pf,int,int);---> This is also a function declaration which return a int value and takes 2 int datatype value and "pf" means a pointer to a function of "pf" type(as explained what is pf)
4.printf("%d\n",proc(f,6,6));---> we are calling proc with argu. ( f ,int,int) = (f,6,6) and proce get called ......and reach the definition of proc(pf,int,int).....in the definition of proc (pf p , int a , int b) we have created a formal argument of "pf" type called "p" and p get intiallized by p = &f ; ......
Line :- return((*p)(a,b)); will expand such that:-
(*p)(a,b) = (*(&f))(a,b) ;[since p = &f since we have passed "f" int pritnf statement ]
(*(&f))(a,b) = f(a,b) = f(6,6) which will return 1(since 6==6) which will return by return statement of proce.....and get printed by printf statement of main :)
 

0 comments to “typedef with With Pointer To Function .”

Post a Comment

Write your tips here...

Deal of the Day

Advertisement here

Advertisement here