0
votes

I was trying to find a bug in my code, and found out that returning a function name was implicitly converted to a bool as true:

bool isArabicNumeral(char arg) { /* Details not important*/ };
bool isValidVarNameFirstChar(char arg) { /* Details not important */ }
bool isValidVarNameContinuationChar(char arg)
{
    return isValidVarNameFirstChar || isArabicNumeral(arg) ? true : false;
    // I forgot to write the brackets after isValidVarNameFirstChar 
    // so the function wasn't called. This always returns true.
}

So I found out that C++ allows conversion to bool wherever it it's useful for such a conversion to take place, so I can do:

void afunction() {};

int main()
{
    bool boolVariable = afunction; // This works
    int intVariable = afunction; // This doesn't work

    return 0;
}

My question is, I understand that there is an implicit conversion from function to bool, but why is it always returning true. Also, what is actually being converted to bool? Is it the function pointer, so that it is in fact returning something like 0xF7B3A1D0, and converting to true as anything non-zero is true? Or is it returning the function typename? Or something else? It's weird, usually when I accidentally leave the brackets after a function my compiler usually says something like "Non-standard use of function call".

Also, how is this a useful a conversion?

2
It's not about being useful. It's simply a derivative of the general language rules. - StoryTeller - Unslander Monica
"how is this a useful a conversion" -- It's not really in this case, but in the general case it makes sense. It's commonplace (particularly in older code) to do if (somePointer) to perform a non-null check. This works just as well for function pointers as it does object pointers. Putting a special case in the language to forbid this conversion when given a named function is arguably bloat. Quite simply, there's no reason to forbid it. It's akin to doing if (1). - cdhowie

2 Answers

1
votes

Is it the function pointer, so that it is in fact returning something like 0xF7B3A1D0, and converting to true as anything non-zero is true?

Yes.

0
votes

Yeah, reason being the bool check just sees if it's not false (aka 0), and if it's not false, then it's true.