Address of Functions

Somewhere (perhaps in C++ : The Complete Reference by Herbert Schildt)I read that the functions also have address in the memory.
I tried to print it using many techniques but obviously failed.
Why so?
Last edited on
Sorry I forgot to put it in the questions category.
What have you tried?

Try the following:

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <cstddef>
int f() {
        return 42;
}
int main()
{
    std::cout << std::hex << std::showbase <<  reinterpret_cast<std::size_t>(f) << '\n';
}


demo: http://ideone.com/5jOTc

A more portable approach, which requires a modern compiler, is to use uintptr_t

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <cstdint>
int f() {
        return 42;
}
int main()
{
    std::cout << std::hex << std::showbase <<  reinterpret_cast<std::uintptr_t>(f) << '\n';
}


demo: http://ideone.com/gyT8C
Last edited on
I don't know anything about -
1.cstdint
2.std::hex
3.std::showbase
4.reinterpret_cast<std::uintptr_t>

Can you please explain them?
cstdint is a C++11 header file, equivalent to C's stdint.h http://en.cppreference.com/w/cpp/types/integer

std::hex is the IO manipulator that makes integer output hexadecimal http://www.cplusplus.com/reference/iostream/manipulators/hex/

std::showbase is the IO manipulator that, for hexadecimal output, makes it so that "0x" is printed http://www.cplusplus.com/reference/iostream/manipulators/showbase/

reinterpret_cast from a pointer to an integer type creates an integer with the value equal to the value stored in the pointer (that is, the RAM address)

std::uintptr_t is the integer type sufficient to hold any valid pointer value
Topic archived. No new replies allowed.