Why does printing a function name returns a value?

后端 未结 3 1867
野趣味
野趣味 2021-01-12 15:41

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

相关标签:
3条回答
  • 2021-01-12 15:57

    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.

    0 讨论(0)
  • 2021-01-12 16:01
    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.

    0 讨论(0)
  • 2021-01-12 16:08

    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.

    0 讨论(0)
提交回复
热议问题