I was learning function pointer. I faced one syntax error. I have implemented sort with comparison function as an additonal arguement.
// working fine
#include<iostream>
using namespace std;
typedef int (*C_MP)(double d);
template<typename X>
X* sort(X* start, X* last,X size, bool (*comp)(X,X)){
for(int i=0;i<size;i++){
for(int j=1;j<size;j++){
X x=*(start+j-1);
X y=*(start + j);
if(!(*comp)(x,y)){
cout<<i<<" "<<x<<" "<<y<<endl;
swap(start[j],start[j-1]);
}
}
}
return start;
}
int fun(double x){
return x;
}
bool comp(float x, float y){
if(x>y){
return 0;
}
return 1;
}
int main(){
C_MP x = fun;
cout<<(*x)(10)<<endl;
float arr[] = {2.1,3.2,6.3,8.4,1.9,0.3};
float* narr = sort<float>(&arr[0],&arr[5],6,&comp);
for(int i=0;i<6;i++){
cout<<*(narr+i)<<endl;
}
}
}
In sort function definition, when I remove brackets from the comp it gives compilation error. I just wanted why this bracket is neccessary or is it just an syntax we need to remember and there is no logic behind it or compiler is confusing it with something else? please give some insights. Function pointers are also used in callbacks. Can you give some small idea/project ,if possible, where I can implement callbacks using function pointer.
// Give compilation error
#include<iostream>
using namespace std;
typedef int (*C_MP)(double d);
template<typename X>
X* sort(X* start, X* last,X size, bool *comp(X,X)){
for(int i=0;i<size;i++){
for(int j=1;j<size;j++){
X x=*(start+j-1);
X y=*(start + j);
if(!(*comp)(x,y)){
cout<<i<<" "<<x<<" "<<y<<endl;
swap(start[j],start[j-1]);
}
}
}
return start;
}
int fun(double x){
return x;
}
bool comp(float x, float y){
if(x>y){
return 0;
}
return 1;
}
int main(){
C_MP x = fun;
cout<<(*x)(10)<<endl;
float arr[] = {2.1,3.2,6.3,8.4,1.9,0.3};
float* narr = sort<float>(&arr[0],&arr[5],6,&comp);
for(int i=0;i<6;i++){
cout<<*(narr+i)<<endl;
}
}
I tried using if similar question existed. I didn't found anything.