Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does printing a function name returns a value?

Tags:

c++

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;
}
like image 420
Prayansh Srivastava Avatar asked Aug 02 '15 11:08

Prayansh Srivastava


3 Answers

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.

like image 121
Thomas Avatar answered Sep 22 '22 10:09

Thomas


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.

like image 35
Serge Rogatch Avatar answered Sep 21 '22 10:09

Serge Rogatch


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.

like image 34
Yu Hao Avatar answered Sep 20 '22 10:09

Yu Hao