Using function pointers
I just wanted to check if i still remembered using pointers in C..Its been quite some time since i have used them,so I tried this simple program this morning ...and thought I'd post it ..
#include
void foo(){
printf("In foo \n");
}
int bar(int i){
printf("In bar\n");
return(i+1);
}
typedef int (*gptr)(int); /* gptr is a function pointer which takes in an int and returns an int */
typedef gptr(*cptr)(gptr); /* cptr is a function pointer which takes in a function ptr of type gptr and returns a function ptr */
gptr cfunct( gptr pf){
gptr rf;
pf(6);
rf=bar;
return(rf);
}
main(){
int ret;
void (*fptr)();
int (*bptr)(int);
gptr pfi,rfi;
cptr cpfi;
fptr=foo;
(*fptr)();
bptr=bar;
ret=(*bptr)(6);
printf("Returned %d from bar\n",ret);
pfi=bar;
ret=pfi(6);
printf("Returned %d from bar\n",ret);
cpfi =cfunct;
pfi=bar;
rfi=cpfi(pfi);
ret=rfi(8);
printf("Returned %d from bar\n",ret);
}
#include
void foo(){
printf("In foo \n");
}
int bar(int i){
printf("In bar\n");
return(i+1);
}
typedef int (*gptr)(int); /* gptr is a function pointer which takes in an int and returns an int */
typedef gptr(*cptr)(gptr); /* cptr is a function pointer which takes in a function ptr of type gptr and returns a function ptr */
gptr cfunct( gptr pf){
gptr rf;
pf(6);
rf=bar;
return(rf);
}
main(){
int ret;
void (*fptr)();
int (*bptr)(int);
gptr pfi,rfi;
cptr cpfi;
fptr=foo;
(*fptr)();
bptr=bar;
ret=(*bptr)(6);
printf("Returned %d from bar\n",ret);
pfi=bar;
ret=pfi(6);
printf("Returned %d from bar\n",ret);
cpfi =cfunct;
pfi=bar;
rfi=cpfi(pfi);
ret=rfi(8);
printf("Returned %d from bar\n",ret);
}
Comments