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 name or definition, and for every time I run it.
EDIT: The answers cleared my doubt, to anyone else who is reading this - Explicitly converting the function name to int works, i.e int k=(int)foo;
This test code will make things more clear:
#include <iostream>
#include <stdio.h>
#include <conio.h>
using namespace std;
void foo(){cout<<'Á';} //FUNCTION IS NEVER CALLED
int main()
{
while(_kbhit()) //JUST TO MAKE SURE BUFFER IS CLEARED
{ getch();} //SAME RESULT WITHOUT THESE TWO STATEMENTS
cout<<foo; //OUTPUT 1
printf("\n%u", foo); //OUTPUT 4199232
/*int k=foo; //CANNOT CONVERT VOID(*)() TO 'INT'*/
return 0;
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With