Check following code:
#include <iostream>
using namespace std;
int& foo() {
static int i = 0;
return i;
}
int main() {
cout << &foo() << endl;
cout << &foo << endl;
return 0;
}
As you see, the first cout
prints address of return value of foo()
which will be static variable i
inside foo()
. For 2nd cout
I was expecting that &foo
returns address of foo()
function, as stated here:
2) If the operand is a qualified name of a non-static member, e.g. &C::member, the result is a prvalue pointer to member function or pointer to data member of type T in class C. Note that neither &member nor C::member nor even &(C::member) may be used to initialize a pointer to member.
But to my surprise, this is my output:
0x5650dc8dc174
1
First one is ok, but 2nd one is 1
? How this happened? To make sure that I have not messed up anything, I wrote this code in C
:
#include <stdio.h>
int foo() {
}
int main(void) {
printf("%p", &foo);
return 0;
}
with following output:
0x55732bd426f0
which works as expected. Have I missed up something in C++
code? or maybe this is because of inlining foo
function (even though it should not be like this)?