Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why function pointer address is printing in bool type in c++?

Tags:

c++

From the below code snippet I am getting the address of the function is 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);
}
like image 296
Abdulvakaf K Avatar asked Dec 19 '22 12:12

Abdulvakaf K


2 Answers

Function pointers aren't convertible to data pointers. You'd get a compiler error if you were to try and assign one to a void* variable. But they are implicitly convertible to bool!

That is why the bool overload for operator<< is chosen over the const void* one.

To force the overload you want, you'd need to use a very strong C++ cast, that will almost completely ignore the 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 that casting and treating function pointers as data pointers is only conditionally supported (from the C++ standard standpoint). Using it for anything other than casting back to the same function pointer will have an implementation specific outcome, that can very greatly among compilers.

like image 200
StoryTeller - Unslander Monica Avatar answered Dec 21 '22 01:12

StoryTeller - Unslander Monica


The overload used is

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

Which prints 1 as your function pointer is not null.

like image 32
Jarod42 Avatar answered Dec 21 '22 02:12

Jarod42