Home > Blockchain >  Why don't we add parenthesis when writing comparator in c ?
Why don't we add parenthesis when writing comparator in c ?

Time:06-01

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()

CodePudding user response:

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.

CodePudding user response:

If you will write

sort(arr.begin(), arr.end(), comparator());

then it means that the argument expression of the function std::sort comparator() must be evaluated. But neither arguments are supplied to the function call comparator(). So the compiler will issue an error message.

On the other hand, if you will write

sort(arr.begin(), arr.end(), comparator);

then the function designator comparator is implicitly converted to a pointer to the function and the function std::sort within itself will call the function using the pointer and supplying two arguments to it.

  • Related