Search code examples
c++visual-studio-codefunction-pointers

Getting C++ Function Address using VSCode & VS


I've tried this piece of code in my VSCode, and theoretically the output should give me the function's address

#include<iostream>
using namespace std;
int getNumber(){
    return 9000;
}

int main(){
    cout<<getNumber<<endl;
    return 0;
}

Once I run the code in VSCode, the output is: 1

So I asked my friend to run the exact same code on Visual Studio (since I don't have VS), and the output is a memory address.

My question is,

  1. Why is the output of that code is different when run in VSCode and VS?
  2. What should I do to be able to get the function's address in VSCode using that exact same code?

Solution

  • std::ostream::operator<< has an overload for bool and a pointer can be implicitly converted to a bool, so the output from VSCode (where you tell us you are compiling with mingw) is correct. Since the address of function getNumber is bound to be non-zero, this becomes true, which equals 1, when converted to a bool, so that's what gets printed.

    On the other hand, MSVC (which is what Visual Studio uses to compile your code) appears to be getting it wrong.

    To be sure that you output the address of the function, you can do:

    cout << (void *) getNumber << endl;
    

    Again, a specific overload for void * ensures that getNumber is then interpreted as an address.


    Addendum: With a sufficiently high warning level set, gcc will warn you about this, see: https://wandbox.org/permlink/J9kxSzLshRQsdt0e