Why does the function pointer address print in a bool type in C ++?

From the code snippet below, I get the function address: 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);
}
+4
source share
2 answers

Function pointers are not converted to data pointers. You would get a compiler error if you tried to assign it to a variable void*. But they are implicitly converted to bool!

That is why overload boolfor is operator<<selected over const void*.

To force the overload you want, you will need to use very strong C ++ translation, which almost completely ignores information about the static type.

#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);
}

, ( ++). - , , , .

+8

ostream& ostream::operator<< (bool val);

1, .

+3

Source: https://habr.com/ru/post/1660181/


All Articles