Thursday, 21 September 2017

Basic demo of function pointer for callback purpose in C++

/*
    Basic demo of function pointer for callback purpose
*/

#include "iostream"
using namespace std;

void meaningOfLife(){
    cout<<"\nHi"<<endl;
}

void printANumber(int num, void (*ptr)()){
    cout<<"\nnum: "<<num;
    (*ptr)(); // simply ptr();

}

int main(){
    void (*p)() = meaningOfLife;
    printANumber(6,p); // can also be called     printANumber(6,meaningOfLife); reason:- function name is pointer to itself

}
/*
    OUTPUT
[pavan@localhost Function-Pointer]$ g++ FPCallBack1.cpp
[pavan@localhost Function-Pointer]$ ./a.out

num: 6
Hi
[pavan@localhost Function-Pointer]$

*/

No comments: