LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C++ : function adress/ Variable adress (https://www.linuxquestions.org/questions/programming-9/c-function-adress-variable-adress-871672/)

LoDam 03-29-2011 05:25 AM

C++ : function adress/ Variable adress
 
Hi LQ,

I have a question regarding function adress.
Maybe it is easier to understand my problem with a bit of code:

Code:


#include <iostream>
  2 using namespace std;
  3 void func(void)
  4 {
  5    cout << "Did you call me?" << endl;
  6 return;
  7 }
  8 int main(int argc,char* argv[])
  9 {
 10    void (*f)() = &func;
 11    int i = 0;
 12
 13    cout
 14        << "without casting :" << endl
 15        << "f: " << f  << " main: " << main << endl
 16        << "with casting :" << endl
 17        << "f:  " << (long)f << " main: " << (long)main
 18        << endl;
 19    cout << "With variables: " << endl << &i << " " << long(&i) << endl;
 20 return 0;
 21 }

and the output I get :

Code:


[Alpha][Tests] ./test_pointfunc
without casting :
f: 1 main: 1
with casting :
f:  4196516 main: 4196550
With variables:
0x7fff10662df4 140733468519924


Why do I get a simple '1' for the function adress when not casted to couble? (while I get an hex adress for a variable). Also, why is it the same result for all the function (I did it here with the main, but if I had another function, I get the same results).

Is it machine specific, is it that I did something wrong, or is it something I didn't understand?

Cheers,
Loic.

dwhitney67 03-29-2011 05:41 AM

The function pointer is interpreted as a bool when passed to the ostream object. You can verify this with:
Code:

#include <iostream>

void func(void)
{
}

int main()
{
  void (*f)() = func;
  void (*g)() = NULL;

  std::cout << "f = " << f << std::endl;
  std::cout << "g = " << g << std::endl;
}

Suffice to say, your question has been asked before; read here for the response.


All times are GMT -5. The time now is 04:23 AM.