Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function name in if statement is converted in a strange way

With this code (valid C++11):

#include <stdio.h>
#include <typeinfo>

bool my_awesome_func(int param) {
  return (param > 1);
}

int main(int argc, char const *argv[]) {
  fprintf(stderr, "type of my_awesome_func: %s\n", 
          typeid(my_awesome_func).name());
  if (my_awesome_func) {
    fprintf(stderr, "WHAT???\n");
  }
  return 0;
}

The question is inside of the if statement. While typeid returns me something that looks like FbiE (which I think is gcc language for function type) I do not understand why this type is being implicitly converted into bool (just an example, also works with int).

Why does the if statement compile and evaluate true?

like image 673
niosus Avatar asked Jan 25 '16 22:01

niosus


1 Answers

There is no casting in your code. A cast is an explicit conversion. I assume you are asking: What does implicit conversion of a function to bool do?

The answer to that is: the function is converted to a function pointer. Then the function pointer is converted to bool via implicit conversion. That conversion is defined as yielding:

  • false for a null function pointer
  • true for any other function pointer

So in your code, the body of if (my_awesome_func) is always entered. (Converting an actual function to a function pointer never yields a null pointer).

like image 82
M.M Avatar answered Nov 06 '22 03:11

M.M