C/C++, function pointer

0. A function pointer is a variable that stores the address of a function that will be called later through that function pointer. 

    Function pointers are among the most powerful tools in C.  It can be used to implement function callback in C. C++ takes a slightly different route for callbacks. 

 // (1)define a function

bool lengthCompare(const string&, const string&){

  return true;

}

// (2)define a function pointer and initialize it 

bool (*pf) (const string&, const string&); 

pf = lengthCompare;

pf = &lengthCompare;

 

// (3)call a function through a function pointer

cmpFcn pf = lengthCompare;  // initialize the pf

pf("hi","bye"); // implicitly dereferenced 

(*pf)("hi","type"); // explicitly dereferenced 

 

// (4)define a type named cmpFcn, this type is a pointer to function.  

typedef bool (*cmpFcn) (const string&, const string&);

typedef int func(int*, int); // func is a function type, not a pointer to a function.

 

// (5)function pointer as a parameter

void useBigger(const string&, const string&, bool (*)(const string&, const string&));

void useBigger(const string&, const string&, bool (const string&, const string&));

 

// (6)function pointer as a return type

int (*ff(int))(int*, int); // is the same as following codes

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

pf ff(int); // ff return a pointer to function

 

// (7)example

 int main(){

  cmpFcn pf1;
  cmpFcn pf2 = 0; 
  cmpFcn pf3 = lengthCompare;
  cmpFcn pf4 = &lengthCompare;

  pf = lengthCompare;
  cout << pf << endl;   // 1
  cout << pf1 << endl;  // 0
  cout << pf2 << endl;  // 0
  cout << pf3 << endl;  // 1
  cout << pf4 << endl;  // 1

  return 0;
}

2. There is no conversation between one pointer to function type and another. 

A function pointer must point to the function whose type is exactly the same as this pointer points to.

3. Benefits of function pointers

    Write flexible functions and libraries that allow the programmer to choose behavior by passing function pointers as arguments.

    This flexibility can also be achieved by using classes with virtual functions.

( Most of the code are coming from C++ primer fourth edition  )

原文链接: https://www.cnblogs.com/sarah-zhang/p/12210931.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C/C++, function pointer

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/324406

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午1:29
下一篇 2023年3月1日 下午1:30

相关推荐