I accidentally printed a function name without the parenthesis and it printed a value. I am just curious about how this happens? Output is same irrespective of the function
A mention of a function name without parentheses is interpreted as a function pointer. The pointer is interpreted as an unsigned int
by the %u
format specifier, which is undefined behaviour but happens to work on most systems.
The reason int k = foo
doesn't work is that a function pointer normally needs a cast to be converted to int
. However, printf
is much more lenient because it uses varargs
to parse its argument string; the type of the arguments is assumed to match the type requested in the format string.
std::cout << foo;
Outputs 1
because foo
is a function pointer, it will be converted to bool
with std::cout
.
To print its address, you need explicitly cast it:
std::cout << reinterpret_cast<void*>(foo) << std::endl;
With printf("\n%u", foo);
, %u
expects unsigned int
, what you saw is the value of the function pointer converted to unsgigned int
.
This statement printf("\n%u", foo);
passes the address of function foo()
to printf
. So the value that gets printed is the address of this function in the memory of the running program.