Search code examples
c++function-pointersimplicit-conversion

Why can you use a function as an if-statement condition without calling it?


I was wondering why both versions of this code have no error:

#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;
}

Condition (1) prints Hello world! despite the fact that I have not passed the variable number into the function check_number in the if-statement.

In case (2), I get not hello world as expected.


Solution

  • if (check_number)
    

    In this context check_number decays to a function pointer, and as the former has an address, the latter is not the null pointer, thus the test succeeds and you enter the if branch.

    That's just the same as if you assign the function to a function pointer without explicitly taking the address of:

    bool(*fPtr)(int) = check_number; // don't need &check_number