Search code examples
c++algorithmsortinglambdacomparator

Why don't we add parenthesis when writing comparator in c++?


Here is a code explaining what I mean.


static bool comparator(int a, int b) {
    if(a > b) return false;
    return true;
}

sort(arr.begin(), arr.end(), comparator); // why don't we write comparator()


Solution

  • Why don't we add parenthesis when writing comparator in c++?

    Because we're not passing the result of calling that function but instead a pointer to that function. In particular, the third argument named comparator to std::sort will implicitly decay to a pointer to that function type due to type decay. You might already be familiar with type decay for built in arrays which also automatically decay to a pointer to their first element. This(a free function to function pointer) is just another instance of type decay.

    If we were to pass comaparator() then we would be passing a value of type bool which is not what is expected. Additionally since comparator takes 2 int arguments and so if we'were to write comparator() it would be invalid because we're not passing any argument to it.

    It is as if you wrote:

    //---------------------------v--------------->note the & operator used here which is optional
    sort(arr.begin(), arr.end(), &comparator);   //this statement is equivalent to the statement that you have in your question 
    

    The above modified statement is equivalent to the statement that you have in your example. The only syntactic difference here is that here we have explicitly used the & to indicate that we're passing a pointer to the function named comparator.