小编Fre*_*e99的帖子

为什么可以使用函数作为 if 语句条件而不调用它?

我想知道为什么这段代码的两个版本都没有错误:

#include <iostream>

bool check_number(int n) {
    return n < 5;
}

int main() {
    int number = 6;

    // (1) prints "Hello World"
    if (check_number)
    // (2) prints "not hello world"
    if (check_number(number))
    {
        std::cout << "Hello world!";
    }
    else
    {
        std::cout << "not hello world";
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Hello world!尽管我没有将变量传递到if 语句中的number函数中,但条件 (1) 仍会打印。check_number

在情况(2)中,我得到了not hello world预期的结果。

c++ function-pointers implicit-conversion

3
推荐指数
3
解决办法
147
查看次数