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?
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 pointertrue
for any other function pointerSo 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).
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