为什么函数向bool存在隐式转换

Why is there Implicit conversion of function to bool?

本文关键字:转换 存在 bool 函数 为什么      更新时间:2023-10-16

我试图在我的代码中找到一个错误,发现返回函数名称被隐式转换为bool为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.
}

所以我发现C 允许转换在任何地方都可以进行这种转换,因此我可以这样做:

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

我的问题是,我知道从函数到布尔有一个隐式转换,但是为什么它总是返回的。另外,实际上是在转换为布尔?它是函数指针,因此实际上它是返回类似0xF7B3A1D0的内容,并且由于非零的内容是正确的吗?还是返回函数TypeName?或者是其他东西?这很奇怪,通常,当我在函数之后不小心离开括号时,我的编译器通常会说"非标准使用功能调用"。

另外,这是如何有用的转换?

是函数指针,因此实际上它是返回诸如0xf7b3a1d0之类的东西,然后转换为true,因为非零的内容是true的?

是。

是的,原因是bool检查只是查看是否不是false(又称0),如果不是false,则是真的。