c++ - Function pointer traps -
from below code snippet getting address of function 1. why ?
#include<iostream> using namespace std; int add(int x, int y) { int z; z = x+y; cout<<"ans:"<<z<<endl; } int main() { int a=10, b= 10; int (*func_ptr) (int,int); func_ptr = &add; cout<<"the address of function add()is :"<<func_ptr<<endl; (*func_ptr) (a,b); }
function pointers aren't convertible data pointers. you'd compiler error if try , assign 1 void*
variable. implicitly convertible bool
!
that why bool
overload operator<<
chosen on const void*
one.
to force overload want, you'd need use strong c++ cast, almost ignore static type information.
#include<iostream> using namespace std; int add(int x, int y) { int z; z = x+y; cout<<"ans:"<<z<<endl; } int main() { int a=10, b= 10; int (*func_ptr) (int,int); func_ptr = &add; cout<<"the address of function add()is :"<< reinterpret_cast<void*>(func_ptr) <<endl; (*func_ptr) (a,b); }
note casting , treating function pointers data pointers officially (from c++ standard standpoint) resulting in ub. though compilers reasonable.
Comments
Post a Comment